C++ 如何定义和使用boost::function with";可选参数";?

C++ 如何定义和使用boost::function with";可选参数";?,c++,boost,function-pointers,optional-parameters,boost-bind,C++,Boost,Function Pointers,Optional Parameters,Boost Bind,我使用的类需要某种回调方法,所以我使用boost::function来存储函数指针 我需要回调函数有一个可选参数,但我发现boost::function不允许我定义类型为的可选参数,所以我尝试了以下代码,它成功了 //the second argument is optional typedef boost::function< int (int, char*)> myHandler; class A { public: //handler with

我使用的类需要某种回调方法,所以我使用boost::function来存储函数指针

我需要回调函数有一个可选参数,但我发现boost::function不允许我定义类型为的可选参数,所以我尝试了以下代码,它成功了

//the second argument is optional  
typedef boost::function< int (int, char*)> myHandler;  

class A   
{  
public:  
     //handler with 2 arguments  
     int foo(int x,char* a) {printf("%s\n",a);   return 0;}; 
     //handler with 1 argument
     int boo(int x) {return 1;};       
}

A* a = new A;  
myHandler fooHandler= boost::bind(&A::foo,a,_1,_2);  
myHandler booHandler= boost::bind(&A::boo,a,_1);    

char* anyCharPtr = "just for demo";  
//This works as expected calling a->foo(5,anyCharPtr)  
fooHandler(5,anyCharPtr);  
//Surprise, this also works as expected, calling a->boo(5) and ignores anyCharPtr 
booHandler(5,anyCharPtr);   
//第二个参数是可选的
typedef boost::functionmyHandler;
甲级
{  
公众:
//具有2个参数的处理程序
intfoo(intx,char*a){printf(“%s\n”,a);返回0;};
//具有1个参数的处理程序
int boo(int x){return 1;};
}
A*A=新的A;
myHandler-foodhandler=boost::bind(&A::foo,A,_1,_2);
myHandler booHandler=boost::bind(&A::boo,A,_1);
char*anyCharPtr=“仅用于演示”;
//这与调用a->foo(5,anyCharPtr)时的预期效果一样
Foodhandler(5,anyCharPtr);
//令人惊讶的是,这也能按预期工作,调用a->boo(5)并忽略anyCharPtr
booHandler(5,anyCharPtr);
我对它的有效性感到震惊,问题是它应该有效吗?它合法吗?

有更好的解决方案吗?

可以说bind->function转换中存在类型安全漏洞。 boost::bind不返回std::function,而是返回一个非常复杂类型的函数对象。就

boost::bind(&A::boo,a,_1);
如上所述,返回的对象具有

boost::_bi::bind_t<
  int, 
  boost::_mfi::mf1<int,A,int>,
  boost::_bi::list2<boost::_bi::value<A*>, boost::arg<1> > 
>
boost::\u bi::bind\u t<
int,
推进:mfi::mf1,

boost::_bi::list2IMO这里奇怪的不是你的
//惊喜在哪里,但是,你可以声明<代码> BooHuffer-作为<代码> MyHyther-< /Cord> Type。如果只有FooHunter也不能将文字绑定到字符**我应该认为它是一个bug还是一个特性?@ GTK:BooS.Bo.DOCs显式地将此调用为一个特性:“ILDJARN -谢谢,我没有意识到这一点——将相应地更新帖子。
template<class A1, class A2> result_type operator()(A1 & a1, A2 & a2)