使用Microsoft Visual C 2013(12.0),在可变模板中的构造函数中使用lambda时遇到编译时错误.我已经设法将其关闭,如下所示(请参阅错误评论的行).它似乎是12.0中的一个错误,在14.0中不存在.我还没有尝试其他版本.有没有关于这个bug的文档,也许是以发布说明的形式阐明了这个bug发生的条件,哪些说明它已经被明确地解决了?
#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;
}
解决方法
截至今天(根据
CppCoreGuidelines),您应该使用{}括号初始化程序.你试了吗?
MyClass a{[] {}};