【发布时间】:2012-09-14 22:02:44
【问题描述】:
我正在 Linux 上进行关于 boost::bind 的 C++ 编码。
boost::bind 的返回数据类型是一个函数对象,它是另一个函数bridge_set_pound_var_func 的输入参数。
但是,bridge_set_pound_var_func 的输入参数必须是函数指针。 bridge_set_pound_var_func 的接口不能改变。
代码如下:
#include <boost/bind.hpp>
#include <iostream>
using namespace boost;
class myA
{
public:
int bridge_set_pound_var_func( int (*pound_var_func)(const char *, char *, void *), void *arg ) { std::cout << "bridge_set_pound_func is called " << std::endl ; return 0; }
};
class myC
{
public:
myA *myOA;
int func(const char * poundVar , char * t1, void * t2);
int myCCall() { myOA->bridge_set_pound_func( (boost::bind(&myC::func, this)), (void *)this ); return 0;}
};
int myC::func(const char * poundVar , char * t1, void * t2)
{
std::cout << "myC::func is called " << std::endl;
return 1;
}
int main()
{
myC myCO ;
myC *m1p = &myCO ;
m1p->myCCall() ;
return 0 ;
}
// EOF
我得到编译错误:
error: no matching function for call to
'myA::bridge_set_pound_func(boost::_bi::bind_t<int (&)(const char*, char*, void*), boost::_mfi::dm<int ()(const char*, char*, void*), myC>, boost::_bi::list1<boost::_bi::value<myC*> > >, void*)'
note: candidates are: int myA::bridge_set_pound_func(int (*)(const char*, char*, void*), void*)
任何帮助将不胜感激。
而且,bridge_set_pound_var_func 的接口不能更改,因为它需要被许多其他函数调用。
这是有效的新代码。但是,“myC::func is called”没有打印出来,为什么?
#include <boost/bind.hpp>
#include <boost/function.hpp>
#include <iostream>
using namespace boost;
class myA
{
public:
int bridge_set_pound_var_func( const boost::function3<int, const char *, char *, void *> f, void *arg ) { std::cout << "bridge_set_pound_var_func is called " << std::endl ; return 0; }
};
typedef int (*funcPtr)(const char *, char *, void *) ;
typedef boost::function0<int&> boostBindFuncType;
class myC
{
public:
myA *myOA;
int func(const char * poundVar , char * t1, void * t2);
int myCCall()
{
std::cout << "myCCall is called " << std::endl;
myOA->bridge_set_pound_var_func( (boost::bind(&myC::func, this, _1, _2, _3)), (void *)this );
return 0;
}
};
int myC::func(const char * poundVar , char * t1, void * t2)
{
std::cout << "myC::func is called " << std::endl;
return 1;
}
int main()
{
myC myCO ;
myC *m1p = &myCO ;
m1p->myCCall() ;
return 0 ;
}
我无法更改被许多其他函数调用的 bridge_set_pound_var_func 的接口。是否可以将 boost::bind 返回的函数对象转换为函数指针?
【问题讨论】:
-
旁注:为什么不使用 C++11
functional库? -
这是一个非常大的项目的一小部分。如何使用 C++11 函数库?谢谢
-
使用更好的名称将使您的示例代码更易于理解。
myA和myC不要告诉我任何事情,并且您不要在示例代码中的任何地方使用f1。f1似乎是myA::bridge_set_pound_func()——对吗?所以myA对象实际上不是你的,那是固定的接口吗? -
只需创建一个辅助函数并将一个指针传递给辅助函数。你可以编写帮助函数来做任何你想做的事情,包括调用
boost::function。
标签: c++ linux boost bind function-pointers