如何使用“可选参数”定义和使用boost :: function?

时间:2011-03-04 10:35:49

标签: 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 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);   

我感到震惊的是它有效,问题是否应该有效,是否合法? 有更好的解决方案吗?

1 个答案:

答案 0 :(得分:3)

可以说是绑定中的类型安全漏洞 - &gt;功能转换。 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> > 
>

std :: function 只检查提供的函数对象是否“兼容”,在这种情况下,它是否可以使用 int 作为第一个参数调用指向char 的指针作为第二个参数。在检查* boost :: bind_t *模板后,我们发现它确实有一个匹配的函数调用操作符:

template<class A1, class A2> result_type operator()(A1 & a1, A2 & a2)

在这个函数中,第二个参数最终被静默丢弃。这是设计的。来自文档:Any extra arguments are silently ignored (...)