可变参数模板中的Lambdas

时间:2016-10-31 21:40:42

标签: c++ templates visual-c++ lambda variadic-templates

使用Microsoft Visual C ++ 2013(12.0),在可变参数模板中的构造函数中使用lambda时遇到编译时错误。我已设法将其煮沸,如下所示(请参阅带有error注释的行)。它似乎是12.0中的一个错误,在14.0中没有出现。我没有尝试过其他版本。是否有关于此错误的任何文档,可能是以发布说明的形式说明了发生此错误的条件以及哪些条款已明确修复?

#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 个答案:

答案 0 :(得分:0)

您需要将不为空的labda函数传递给类构造函数 像这样:

MyClass a([] {cout << "This should work"; });

答案 1 :(得分:-1)

截至今天(根据CppCoreGuidelines),您应该使用{}括号初始值设定项。你试过吗?

 MyClass a{[] {}};