2011-03-04 79 views
4

我正在使用需要某種回調方法的類,所以我使用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); 

我很震驚,它的工作,問題是它應該工作,並且它是合法的嗎?
有沒有更好的解決方案?

+1

國際海事組織什麼是奇怪的不是你的''驚喜'是,但你可以聲明'booHandler'作爲'myHandler'類型。 – Benoit 2011-03-04 10:55:06

+0

,如果只有fooHandler也會因將文字綁定到char * – CashCow 2011-03-04 11:10:05

回答

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 ::功能僅檢查所提供的功能目的是「相容的」,在這種情況下,無論它可用int作爲第一個參數和一個作爲第二個參數指向char。考察了*的boost :: bind_t *模板,我們可以看到,它確實有一個匹配的函數調用操作:

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

在這個函數中的第二個參數最終被丟棄。這是設計。從文檔:Any extra arguments are silently ignored (...)

+0

而失敗,我應該認爲它是一個錯誤還是一個特性? – 2011-03-04 19:14:49

+0

@GTK:boost.bind文檔明確地將其稱爲一個特性:http://www.boost.org/doc/libs/release/libs/bind/bind.html#with_functions – ildjarn 2011-03-05 11:53:56

+0

@ildjarn - 謝謝,我wasn不知道 - 會相應地更新帖子 – decltype 2011-03-06 10:07:37

相關問題