c++ - 构造函数中的 std::bind 到类中的回调方法

标签 c++ c++11 stdbind

我有一个 Foo 类,它在 Bar 类中实例化。

我需要将 m_foocallback 分配给名为 xpto()Bar 方法。 我应该可以在这里使用 std::bind,对吗?我的代码有什么问题?

Foo 类:

class Foo
{
public:
   Foo(std::function<void()> cb);
}

酒吧类:

class Bar
{
public:
   Bar(std::function<void()> cb);

   void xpto();
private:
   Foo m_foo;
}

Bar::Bar(std::function<void()> cb)
: m_foo(std::bind(&xpto)) // ERROR!!!?
{}

最佳答案

你对 bind() 的使用有点不对:

class Bar
{
public:
   Bar(std::function<void()> cb);

   void xpto();
private:
   Foo m_foo;
}

Bar::Bar(std::function<void()> cb)
: m_foo(std::bind(&Bar::xpto, this)
{}

那应该行得通。不过,我不确定为什么要为 Bar 的构造函数提供 cb 参数。

关于c++ - 构造函数中的 std::bind 到类中的回调方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32993031/

相关文章:

c++ - 如何处理 Qt5 关闭事件以终止?

c++ - 在可变扩展中排序

c++ - 无法在数组 C++ 中找到最高/最低元素

c++ - 映射值类型的decltype?

c++ - 如何传递参数来 boost asio async_accept

c++ - 带有 unique_ptr 参数的 std::function

c++ - 未找到 Xcode C++ 标准库

c++ - 带有可变参数的 std::function 列表如何工作

C++ 11:std::thread池化?

c++ - std::async 使用绑定(bind)到 lambda 的右值引用