【发布时间】:2016-02-13 11:33:11
【问题描述】:
我正在尝试使用 boost::bind boost::function 实现某些目标,但无法使其工作。
我看到how to bind a member function 的对象带有一些参数,稍后将用作 void/void 函数。但是如何将它绑定到任何对象。
我想要一个指向我的类的成员函数(可以与类的任何对象一起使用)的指针,并带有绑定的参数:
#include "boost/function.hpp"
#include "boost/bind.hpp"
class A
{
public:
A() {}
void func1( int i );
void func2( const std::string& s );
static void dispatch( std::vector<A>& vect, /* boost::function parameter "func" */ ) // what parameter should I set?
{
for ( std::vector<A>::iterator iter = vect.begin();
iter != vect.end();
++iter )
{
// what syntax should I use?
//(*iter).(*func)();
}
}
};
int main()
{
std::vector<A> vect;
// have func1(3) be called for all objects contained in vect
// this does not compile because boost expects an object to bind the function to
A::dispatch( vect, boost::bind( boost::mem_fn(&A::func1), 3 ) );
// have func2("hello") be called for all objects contained in vect
// this does not compile because boost expects an object to bind the function to
A::dispatch( vect, boost::bind( boost::mem_fn(&A::func2), "hello" ) );
}
我试过了:
static void dispatch( const std::vector<A>& vect, boost::_mfi::mf0<void, A> func )
...
boost::_mfi::mf1<void,A,int> func( boost::mem_fn(&A::func1) );
boost::_mfi::mf0<void,A> binded( boost::bind( func, 3 ) );
A::dispatch( vect, binded );
但是编译失败:
Erreur 1 error C2664: 'boost::_mfi::mf0<R,T>::mf0(void (__thiscall A::* )(void))' : impossible de convertir le paramètre 1 de 'boost::_bi::bind_t<R,F,L>' en 'void (__thiscall A::* )(void)' b:\dev\vobs_bci\public\lib\btle\src\btle\notifierdispatcher.cpp 99
注意:我很遗憾还没有使用 C++11,所以请不要auto...;-)
【问题讨论】:
-
在得到答案后编辑问题(以删除 const)并不是很优雅。当然,把
const从我的回答中放到各个地方,然后 -
@sehe:对不起,我只是在评论你的回答。尝试删除代码中的所有
const,但无法编译,报告impossible de convertir le paramètre 2 de 'boost::_bi::bind_t<R,F,L>' en 'boost::function<Signature> &'
标签: c++ boost member-function-pointers boost-bind boost-function