2016-11-06 50 views
2

我希望在使用lambdas時自動扣除接受函數的模板函數的參數。這個例子說明我的一些選項:VS2012在使用+ [] {}巫術時抱怨

template <class T> 
void foo(void (*func)(T)) { 
    T val; 
    // do something with val and func... 
} 

int main() { 
    auto pfunc0   = [] (int) { /*...*/ }; 
    void (*pfunc1)(int) = [] (int) { /*...*/ }; 
    auto* pfunc2  = +[] (int) { /*...*/ }; 

    foo(pfunc0);  // not ok 
    foo<int>(pfunc0); // ok, but redundant 
    foo(pfunc1);  // ok, but redundant 
    foo(pfunc2);  // ok 
} 

pfunc2使用一招我在這裏學到:Obtaining function pointer to lambda?。所以實際上我應該對pfunc2的情況感到滿意,因爲它是簡潔且不重複的代碼,不幸的是Visual C++ 2012 IDE抱怨它是錯誤的代碼,即使它編譯得很好。

是否有針對此問題的任何解決方法或建議?

IDE錯誤信息:

在 「自動* pfunc2」 行:IDE強調 '自動',並說

Error: cannot deduce 'auto' type 

也是它強調 '[' 的地方抱怨

Error: more than one conversion function from "lambda[]void (int)->void" to a build-in type applies: 
function "lambda[]void (int)->void::operator void (*)(int)() const" 
function "lambda[]void (int)->void::operator void (*)(int)() const" 
function "lambda[]void (int)->void::operator void (*)(int)() const" 
+0

我沒有獲得VS2012,但你嘗試過'富(+ pfunc0);'? – krzaq

+0

@krzaq我用錯誤消息更新了我的問題。我嘗試了你的建議,但它沒有改變任何東西(相同的錯誤信息)。 – testman

+0

@testman我不好,我完全錯過了! – Quentin

回答

1

這與this bug(封閉爲「按設計」)有關。 VC++支持x86和lambda上的幾個調用約定,空捕捉列表爲它們提供轉換。這就是爲什麼有歧義。

不幸的是,沒有列出您尚未嘗試過的解決方法。

順便說一句,這個錯誤被列爲固定在Visual C++ 2015 Update 2

+0

我安裝了Visual Studio Community 2015版本14.0.25431.01更新3現在不僅IDE和編譯器抱怨:/ – testman

+0

@testman我記得有一個與Visual Studio 2015命名混淆,有兩個版本被命名爲非常類似的是不同的東西:https://pay.reddit.com/r/cpp/comments/56ecje/psa_visual_studio_15_and_visual_studio_2015_are_2/也許你'是那個的受害者? – krzaq