Search code examples
c++boostboost-signals2

Error when boost signals2 connect with void() bound


When I try to compile this code I get the error

In constructor 'Foo::Foo()': 15:40: error: 'bind' was not declared in this scope

#include <functional>
#include <boost/signals2.hpp>

class Foo {
public:
    Foo();
    void slot1(int i);
    void slot2();
    boost::signals2::signal<void (int)> sig1;
    boost::signals2::signal<void ()> sig2;
};
Foo::Foo() {
    sig1.connect(bind(&Foo::slot1, this, _1));  //  O K !
    sig2.connect(bind(&Foo::slot2, this));      //  E R R O R !
}
void Foo::slot1(int i) { }
void Foo::slot2() { }

int main() {
  Foo foo;
  foo.sig1(4711);
  foo.sig2();
}

What irritates me is that sig1.connect(...) works but not sig2.connect(...). If I use boost::bind() instead it works also on sig2.connect(...)

sig2.connect(boost::bind(&Foo::slot2, this));        // O K !

Can somebody explain why bind() works with slot1 but not slot2?

Here the code to "play" with it online: http://cpp.sh/32ey


Solution

  • sig1 works because the argument _1 is refers to a type in the boost namespace. This allows the compiler to find boost::bind through ADL, since it is in the same namespace. However, sig2 does not, since none of the arguments are in the boost namespace.

    You will either need to say using namespace boost, using boost::bind, or explicitly make the call to boost::bind to resolve the issue.