我想让这段代码正常工作,我该怎么办?
在最后一行给出此错误。
我做错了什么? 我知道boost :: bind需要一种类型,但我没有得到。帮助class A
{
public:
template <class Handle>
void bindA(Handle h)
{
h(1, 2);
}
};
class B
{
public:
void bindB(int number, int number2)
{
std::cout << "1 " << number << "2 " << number2 << std::endl;
}
};
template < class Han > struct Wrap_
{
Wrap_(Han h) : h_(h) {}
template<typename Arg1, typename Arg2> void operator()(Arg1 arg1, Arg2 arg2)
{
h_(arg1, arg2);
}
Han h_;
};
template< class Handler >
inline Wrap_<Handler> make(Handler h)
{
return Wrap_<Handler> (h);
}
int main()
{
A a;
B b;
((boost::bind)(&B::bindB, b, _1, _2))(1, 2);
((boost::bind)(&A::bindA, a, make(boost::bind(&B::bindB, b, _1, _2))))();
/*i want compiled success and execute success this code*/
}
答案 0 :(得分:1)
您遇到的问题是您正在尝试绑定到模板化函数。在这种情况下,您需要指定要调用绑定方法的模板类型。
方法A::bindA
正在发生这种情况。请参阅下面的main代码片段,它使用提供的类正确编译。
顺便提一下,在示例中,我使用boost::function(要绑定的姐妹库)来指定正在使用的函数指针的类型。我认为这使得它更具可读性,并强烈建议您在继续使用bind时熟悉它。
#include "boost/bind.hpp"
#include "boost/function.hpp"
int main(int c, char** argv)
{
A a;
B b;
typedef boost::function<void(int, int)> BFunc;
typedef boost::function<void(BFunc)> AFunc;
BFunc bFunc( boost::bind(&B::bindB, b, _1, _2) );
AFunc aFunc( boost::bind(&A::bindA<BFunc>, a, make(bFunc)) );
bFunc(1,2);
}