2013-04-09 22 views
0

我使用boost ::功能是這樣的:的boost ::綁定的隱式轉換提振::函數或函數指針

template<class T1> 
void run(boost::function<void (T1)> func, string arg) 
{ 
    T1 p1 = parse<T1>(arg); 
    func(p1); 
} 

當這樣使用,一切正常:

void test1(int i) 
{ 
    cout << "test1 i=" << i << endl; 
} 

... 

boost::function<void (int)> f = &test1; 
run(f, "42"); 

我希望能夠將原始函數指針直接傳遞,所以我超載這樣的run()函數:

template<class T1> 
void run(void (*func)(T1), string arg) 
{ 
    T1 p1 = parse<T1>(arg); 
    (*func)(p1); 
} 

... 

run(&test1, "42"); // this is OK now 

現在,我想能夠將boost :: bind的結果傳遞給run()函數。就像這樣:

void test2(int i, string s) 
{ 
    cout << "test2 i=" << i << " s=" << s << endl; 
} 

... 

run(boost::bind(&test2, _1, "test"), "42"); // Edit: Added missing parameter 42 

但是這不會編譯:編輯

bind.cpp: In function ‘int main()’: 
bind.cpp:33:59: error: no matching function for call to ‘run(boost::_bi::bind_t<void, void (*)(int, std::basic_string<char>), boost::_bi::list2<boost::arg<1>, boost::_bi::value<std::basic_string<char> > > >, std::string)’ 
bind.cpp:33:59: note: candidates are: 
bind.cpp:7:6: note: template<class T1> void run(boost::function<void(T1)>, std::string) 
bind.cpp:14:6: note: template<class T1> void run(void (*)(T1), std::string) 

我應該如何運行超載()接受的boost :: bind()的?

編輯2

我知道我能做到這一點是這樣的:

boost::function<void (int)> f = boost::bind(&test2, _1, string("test")); 
run(f, "42"); 

但我想使用是更簡潔。

編輯3

更改的run()的原型來自run(boost::function<void (T1)>, T1)run(boost::function<void (T1)>, string)闡述實際使用情況。參考。伊戈爾R.的回答

整個源文件可以得到here

+0

沒有「隱式投射」這樣的事情。強制轉換是您在源代碼中編寫的內容,以告知編譯器進行轉換。編譯器可以在沒有轉換的情況下進行轉換;這種轉換是「隱式轉換」。當你使用強制轉換時,它是一個「顯式轉換」。 – 2013-04-09 10:03:10

+0

確實。問題標題應該改變。 – anorm 2013-04-09 11:05:42

回答

1

無論function也沒有bind的結果類型可以轉化爲一個函數指針,所以不能將它們與當前傳遞給run功能簽名。

但是,你可以改變run簽名,以允許它接受任何調用

template<class F, class A1> 
void run(F f, A1 arg) 
{ 
    f(arg); 
} 

現在你可以將一個指針傳遞功能,粘合劑,boost::function或者您希望什麼都調用 - 只要因爲它期望1個參數。 (但是請注意,使用這個微不足道的簽名run將不會forwardf無縫對應的參數。)

+0

是的,解決了我描述的問題(+1)。但是,實際的run()函數需要知道參數的類型,參數不是真實世界函數的一部分。 – anorm 2013-04-09 07:55:08

+0

真實世界函數使用參數類型來調用一個模板化的字符串解析器,以便我可以調用一個函數,給它一個字符串參數,並且run()函數將參數解析爲正確的類型並調用函數 – anorm 2013-04-09 07:56:47

+0

我編輯過這個問題以反映這一要求。 – anorm 2013-04-09 08:45:38