c++ - 将回调绑定(bind)到模板化对象

标签 c++ templates boost-bind

我有一个包含回调的模板类,存储为 std::function

typedef std::function<void()> func_t;

template<typename T>
struct A
{
   T someMember;
   func_t callback;
};

此回调由某种机制 (boost::asio) 调用,我想传递参数,因此我将它们绑定(bind):

例如:

void a_callback( int v )
{
    std::cout << "value=" << v << "\n";
}

然后我以这种方式将其存储在对象中。

enum EN { ONE, TWO };

int main()
{
    A<EN> a;

    a.callback = boost::bind( a_callback, 42); // ok
    a.callback(); // ok
}

到目前为止,一切都很好。

但现在我想将对象本身传递给回调函数,以便它可以在其上做事。回调变为模板化,因为对象类是:

template<typename T>
void b_callback( A<T>& b, int v )
{
    std::cout << "value=" << v << "\n";
}

但是试图绑定(bind)它失败了:

int main()
{
    A<EN> a2;  
    a2.callback = boost::bind( b_callback, a2, 42); 
}

Clang 说:

error: no matching function for call to 'bind'
    a2.callback = boost::bind( b_callback, a2, 42); // build error
/usr/local/include/boost/bind/bind.hpp:1891:5: note: candidate template ignored: couldn't infer template argument 'R'
    BOOST_BIND(F f, A1 a1, A2 a2)
/usr/local/include/boost/bind/bind.hpp:1868:20: note: expanded from macro 'BOOST_BIND'
#define BOOST_BIND bind

Full code here (coliru)

我做错了什么?我该如何管理?

最佳答案

您需要实例化一个具有具体类型的函数模板ZH:

a2.callback = boost::bind(&b_callback<EN>, a2, 42);

因为 b_callback 是函数模板,而不是函数。

EXAMPLE

关于c++ - 将回调绑定(bind)到模板化对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48526855/

相关文章:

c++ - Boost::bind 与对象占位符

c++ - 如何在 C++ 中安全地销毁 Posix 线程池

c++ - 使用自定义 header 进行 ffplay 编译

c++ - Rcpp - 如何在 C++ 代码中使用分布函数

python - 在 Windows XP 中从 C++ 程序执行 Python 脚本

c++ - 是否可以从构造函数自动推导出基类模板参数?

javascript - 如何在 Javascript 中的 for 循环内 append html 模板?

javascript - 我如何使用这个 JQuery 插件来移动对象的 X 个位置?

c++ - 使用嵌套的 boost::binds

c++ - C++14 中纯右值的 Cv 限定