我正在使用需要某種回調方法的類,所以我使用boost :: function來存儲函數指針。如何用「可選參數」定義和使用boost :: function?
我需要回調有一個可選的參數,但我發現的boost ::功能不會讓我定義可選參數的一種類型,所以我嘗試下面的代碼和它的工作..
//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);
我很震驚,它的工作,問題是它應該工作,並且它是合法的嗎?
有沒有更好的解決方案?
國際海事組織什麼是奇怪的不是你的''驚喜'是,但你可以聲明'booHandler'作爲'myHandler'類型。 – Benoit 2011-03-04 10:55:06
,如果只有fooHandler也會因將文字綁定到char * – CashCow 2011-03-04 11:10:05