c++ - boost signals2 与 void() 绑定(bind)连接时出错

标签 c++ boost boost-signals2

当我尝试编译这段代码时出现错误

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 boostusing boost::bind,或者显式调用boost::bind解决问题。

关于c++ - boost signals2 与 void() 绑定(bind)连接时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34946369/

相关文章:

c++ - 什么是命名对象?

c++ - 如何绑定(bind)、存储和执行 std::function 对象?

boost - C++/Cli : Could not load file or assembly X or one of its dependencies. 不是有效的 Win32 应用程序。 (来自 HRESULT 的异常:0x800700C1)

c++ - 为什么 boost::signals2::signal<T>::connect 需要复制构造函数?

C++:带有一组指针容器的锁定机制

c++ - 为什么 Visual Studio 在调试时以不同方式对待 ANSI 转义代码?

c++ - 如何从函数/类接收 map<A, B>&?

c++ - 使用 boost::asio::async_read() 的问题

linux - Sigalrm(linux信号)

c++ - boost::signals2 对于简单的应用程序是否矫枉过正?