c++boostboost-signalsboost-signals2

Problems compiling boost signal2


Why does this simple example not compile, and how can I get around the problem?

#include <iostream>
#include <boost/signals2/signal.hpp>

struct HelloWorld {
    HelloWorld() {
        i = 0;
    }

    void operator()() {
        std::cout << "I is: " << i++ << std::endl;
    }

    void setup () {
        sig.connect(this);
    }

    void run () {
        sig();
    }

    boost::signals2::signal<void ()> sig;

    private:
        int i;
};

int main()
{
  HelloWorld hello;
  hello.setup();
  hello.run();
  hello.run();
  hello.run();

  return 0;
};

Solution

  • You are trying to connect to a pointer, which isn't possible. Instead you need to connect to a reference to your object:

    void setup () {
        sig.connect(boost::ref(*this));
    }