2013-08-01 69 views
1

重載方法::如何實現以下重載方法調用綁定使用升壓功能

class Foo { 
    void bind(const int,boost::function<int (void)> f); 
    void bind(const int,boost::function<std::string (void)> f); 
    void bind(const int,boost::function<double (void)> f); 
}; 

首次嘗試

SomeClass c; 
Foo f; 
f.bind(1,boost::bind(&SomeClass::getint,ref(c)); 
f.bind(1,boost::bind(&SomeClass::getstring,ref(c))); 
f.bind(1,boost::bind(&SomeClass::getdouble,ref(c))); 

然後我發現了一個possible answer所以嘗試這樣做: -

f.bind(static_cast<void (Foo::*)(int,boost::function<int(void)>)>(1,boost::bind(&SomeClass::getint))); 

這看起來很醜但可能工作嗎?

,但給錯

error C2440: 'static_cast' : cannot convert from 'boost::_bi::bind_t<R,F,L>' to 'void (__cdecl Foo::*)(int,boost::function<Signature>)' 

任何想法我可以做這個工作超載。我懷疑類型擦除正在發生,但編譯器顯然識別重載的方法,因爲Foo.cpp編譯得很好

回答

2

您鏈接到的可能答案是解決一個不同的問題:在函數重載時選擇一個指向該函數的指針。解決方案是顯式轉換爲正確的函數類型,因爲只有正確的函數可以轉換爲該類型。

你的問題是不同的:調用函數時重載之間的選擇,當沒有明確轉換到任何重載的參數類型。你可以明確地轉換爲函數類型:

f.bind(1,boost::function<int (void)>(boost::bind(&SomeClass::getint,boost::ref(c)))); 

,或者在C++ 11,使用lambda:

f.bind(1,[&]{return c.getint();}); 

(你可能寧願std::functionboost::function在C++ 11)。

+0

完美地工作,是的,我切換到std :: function。 我猜測沒有辦法讓編譯器通過使用工廠函數來推斷鑄造參數? – Ronnie