std :: bind的返回類型是(有意)未指定的。它在std :: function中是可存儲的。如何避免使用std :: bind()臨時對象顯式強制轉換?
下面的示例程序演示瞭如何將std :: bind()返回的臨時對象顯式轉換爲std :: function以調用fn1()。
如果std :: bind的返回類型是可知的,我可以重載回調構造函數&將不再需要顯式強制轉換std :: bind臨時對象。
有什麼辦法可以避免顯式轉換嗎?
// g++ -std=c++11 test.cxx
#include <functional>
using std::placeholders::_1;
class A
{
public:
void funcA (int x) { }
};
class Callback
{
public:
Callback() = default;
Callback (std::function<void(int)> f) { }
// Wish we knew the return type of std::bind()
// Callback (return_type_of_std_bind f) { }
};
void fn0 (std::function<void(int)> f) { }
void fn1 (Callback cb) { }
int main (void)
{
A a;
fn0(std::bind(&A::funcA, &a, _1)); // ok
fn1(std::function<void(int)>(std::bind(&A::funcA, &a, _1))); // ok, but verbose
fn1(std::bind(&A::funcA, &a, _1)); // concise, but won't compile
}
可能不相關,但我在Linux上使用gcc 4.7.2。
你會得到什麼編譯錯誤? –
而不是試圖知道什麼是(設計)不應該知道,不問這個問題。不要試圖知道類型,寫一個不需要知道類型的構造函數......在這一點上你應該考慮「模板」。 –