2016-10-31 142 views
11

使用Microsoft Visual C++ 2013(12.0)時,在可變參數模板中使用構造函數中的lambda時遇到了編譯時錯誤。我已經設法將其煮沸,如下所示(請參閱error評論的行)。它似乎是12.0中的一個缺陷,在14.0中不存在。我還沒有嘗試過其他版本。有沒有關於這個bug的任何文檔,可能是發佈說明的形式,它闡明瞭這個bug發生的條件,並說明它已被明確修復?可變參數模板中的Lambdas

#include <functional> 

// a simple method that can take a lambda 
void MyFunction(const std::function<void()>& f) {} 

// a simple class that can take a lambda 
class MyClass 
{ 
public: 
    MyClass(const std::function<void()>& f) {} 
}; 

// non-templated test 
void test1() 
{ 
    MyFunction([] {}); // OK 
    MyClass([] {}); // OK 
    MyClass o([] {}); // OK 
} 

// non-variadic template test 
template<typename T> 
void test2() 
{ 
    MyFunction([] {}); // OK 
    MyClass([] {}); // OK 
    MyClass o([] {}); // OK 
} 

// variadic template test 
template<typename... T> 
void test3() 
{ 
    MyFunction([] {}); // OK 
    MyClass([] {}); // OK 
    MyClass a([] {}); // error C4430: missing type specifier - int assumed. Note: C++ does not support default-int 
         // error C2440: 'initializing' : cannot convert from 'test3::<lambda_12595f14a5437138aca1906ad0f32cb0>' to 'int' 

    MyClass b(([] {})); // putting the lambda in an extra() seems to fix the problem 
} 

// a function using the templates above must be present 
int main() 
{ 
    test1(); 
    test2<int>(); 
    test3<int, int, int>(); 
    return 1; 
} 
+2

我剛加了'#include '並編譯。我用微軟Visual Studio社區2015 版本14.0.25431.01更新3 – wally

+0

奇怪。我在我的代碼中包含'#include '(忘記包含在複製粘貼中),但它仍然對我抱怨。 –

+1

由於gcc&clang接受代碼([Demo](http://coliru.stacked-crooked.com/a/86fa0b4c990af350))。我會說msvc錯誤(甚至更多與您的模板和可變模板測試)。 – Jarod42

回答

-1

截至今天(根據CppCoreGuidelines),你應該使用括號{}初始化。你試過了嗎?

MyClass a{[] {}};