2017-05-25 98 views
0

考慮下面的代碼的std ::函數的std ::綁定拉姆達超載歧義

class my_class { 
public: 
struct my_struct { 
    int i; 
}; 
std::function<void(my_struct&)> func; 
my_class() { 
    func = std::bind([this](my_struct& s) { s.i = 5; }); 
} 
}; 

在2017年VS我收到以下錯誤:

錯誤C2440:初始化:不能從轉換'std :: _ Binder>'到'std :: function' 注意:沒有構造函數可以採用源類型,或者構造函數的重載解析模糊不清

有什麼想法可以解決模糊問題?

回答

3

這是有史以來最沒有幫助的編譯器錯誤。問題是,你想

func = std::bind([this](my_struct& s) { s.i = 5; }, std::placeholders::_1); 
//             ^^^^^^^^^^^^^^^^^^^^^ 

std::bind(f)的意思是「給我一個g,從而g(/* anything */)f()

你需要的,如果你想通過傳遞參數使用佔位符。

(我假設你的真實代碼做的比這更復雜一些,因爲你不需要bind或在你顯示的代碼中捕獲this)。

+0

感謝此工作! – schuess

2

std::bind或多或少已經在C++ 11中過時了。只需使用lambda代替。

class my_class 
{ 
public: 
    struct my_struct { 
    int i; 
    }; 
    my_class() 
    : func ([](my_struct& s) { s.i = 5; }) {} 
private: 
    std::function<void(my_struct&)> func; 
}; 
+0

Y你的意思是C++ 14。你仍然需要'std :: bind'來支持將東西移動到C++ 11中的lambda上下文中,而不是複製。 – StoryTeller

+0

@StoryTeller在C++ 11中它*幾乎*過時(我說*或多或少*)。在C++ 14中,它甚至更多(完全?)過時。 – Walter

+0

如果有實際需要的用例,我不認爲可以說它已經過時了。但也許我只是分裂頭髮。它在C++ 14中絕對沒有用處。 – StoryTeller