我正在使用一个需要某种回调方法的类,所以我使用 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);
我很震惊它的工作,问题是它应该工作,它是合法的吗?
有更好的解决方案吗?