c++ - double boost::bind 导致编译时错误

标签 c++ boost bind functor boost-bind

下面的代码给出了第17行引起的编译错误:

#include <boost/bind.hpp>
#include <boost/function.hpp>

void func()
{}

class A{
public:

    template <typename T>
    static void foo(T const& arg){}

    template <typename T>
    void bar(T const& arg){
        boost::bind(&A::foo<T>, arg);  //OK
        boost::function<T> functor1 = boost::bind(func); //OK
        boost::function<T> functor2 = boost::bind(&A::foo<T>, arg); //ERROR, LINE 17
    }
};

int main()
{
    A obj1;
    obj1.bar(func);
}

问题是,第17行的functor2的原型(prototype)应该是什么?
如果我真的想保持 functor2 的原型(prototype)为“boost::function,如何让 boost::bind 返回这样的类型?

编译错误是:usr/include/boost/bind/bind.hpp:253: error: invalid initialization of reference of type 'void (&)()' from expression of type 'void (*) ()'
什么意思?

最佳答案

foo(T const& arg) 采用引用参数。为了通过 boost::bind 传递引用参数,您需要用 boost::ref 包装它。

boost::function<T> functor2 = boost::bind(&A::foo<T>, boost::ref(arg));

关于c++ - double boost::bind 导致编译时错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10112761/

相关文章:

c++ - 如何从任何链接下载数据?

c++ - Boost C++ 架构 x86_64 的 undefined symbol

javascript - Jquery 选择器在添加的 dom 元素上没有动态行为

c++ - 正则表达式问题

c++ - 使用 conan 仅安装 boost 的一部分

Javafx:绑定(bind) Hbox 间距?

c++ - 了解绑定(bind)

c++ - C++中如何判断一个整数类型是否是内置类型?

c++ - 我应该使用 Initialize-on-demand 惯用语吗?如果是,如何使用?

c++ - c++ 数组上使用的 delete[] 运算符的理解问题