4

我正在使用一个需要某种回调方法的类,所以我使用 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);   

我很震惊它的工作,问题是它应该工作,它是合法的吗?
有更好的解决方案吗?

4

1 回答 1

3

可以说是绑定 -> 函数转换中的类型安全漏洞。 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)

在这个函数内部,第二个参数最终被默默地丢弃。这是设计使然。从文档中:任何额外的参数都会被忽略(...)

于 2011-03-04T12:27:06.933 回答