当我尝试编译这段代码时出现错误
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();
}
令我恼火的是 sig1.connect(...)
有效但 sig2.connect(...)
无效。
如果我改用 boost::bind() 它也适用于 sig2.connect(...)
sig2.connect(boost::bind(&Foo::slot2, this)); // O K !
有人可以解释为什么 bind() 适用于 slot1 但不适用于 slot2 吗?
这里是在线“玩”它的代码:http://cpp.sh/32ey
最佳答案
sig1 有效是因为参数 _1
是指 boost
命名空间中的类型。这允许编译器通过 ADL 找到 boost::bind
,因为它在同一个命名空间中。但是,sig2 没有,因为没有任何参数在 boost
命名空间中。
您需要说using namespace boost
、using boost::bind
,或者显式调用boost::bind
解决问题。
关于c++ - boost signals2 与 void() 绑定(bind)连接时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34946369/