2015-09-14 32 views
2

給定函數工作:爲什麼汽車不能與某些lambda表達式

void foo(std::function<void(int, std::uint32_t, unsigned int)>& f) 
{ 
    f(1, 2, 4); 
} 

爲什麼這個編譯:

std::function<void(int a, std::uint32_t b, unsigned int c)> f = 
    [] (int a, std::uint32_t b, unsigned int c) -> void 
{ 
    std::cout << a << b << c << '\n'; 
    return; 
}; 

這無法編譯:

auto f = 
    [] (int a, std::uint32_t b, unsigned int c) -> void 
{ 
    std::cout << a << b << c << '\n'; 
    return; 
}; 

與錯誤:

5: error: no matching function for call to 'foo' 
    foo(f); 
    ^~~ 
6: note: candidate function not viable: no known conversion from '(lambda at...:9)' to 'std::function<void (int, std::uint32_t, unsigned int)> &' for 1st argument 
void foo(std::function<void(int, std::uint32_t, unsigned int)>& f) 
    ^
+0

您是否試過使用不同的編譯器?嘗試使用clang和gcc是個好主意。 – user1095108

+0

可能的重複:https://stackoverflow.com/questions/1565600 –

回答

13

拉姆達不是std::function。因此,調用foo函數需要從lambda中構建臨時對象std::function,並將此臨時值作爲參數傳遞。但foo函數需要std::function類型的可修改左值。顯然,一個臨時值不能被非const左值引用所約束。以爲例改爲:

void foo(std::function<void(int, std::uint32_t, unsigned int)> f) 
{ 
    f(1, 2, 4); 
} 
+2

通過'const&'捕獲應該也能工作,對吧? –

+0

@dau_sama:是的 –

相關問題