使用 Microsoft Visual C++ 2013 (12.0) 时,我在可变参数模板中的构造函数中使用lambda表达式时遇到了编译时错误。我已经将其简化为下面所示(请查看带有error
注释的行)。看起来这是一个12.0版本的bug,在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;
}
编辑/更新: MSVC 2013编译器似乎存在这个错误,最新版本已经修复了。GCC和clang编译器没有显示任何错误。
#include <functional>
,然后它就编译通过了。我使用的是 Microsoft Visual Studio Community 2015 版本 14.0.25431.01 Update 3。 - wallyMyClass a{[] {}};
这对你来说可行吗?老实说,这是编译器的缺陷,所以除非你很幸运地让Stephen Lavavej看到这个问题,否则没有真正的解释为什么会发生这种情况。 - AndyGMyClass
的构造函数,但它错误地将其识别为使用int
。或者B)编译器无法将MyClass
视为类型说明,因此推断a
是一个int
,然后不允许使用lambda对其进行初始化。后者似乎更有可能。 - Michael Gunter