c++ - 使用 Visual Studio 2015 : error C3546 在 lambda 中扩展参数包

标签 c++ visual-c++ c++14

正在关注 this question ,我尝试编译以下代码:

template<typename... Types>
auto for_each(type_list<Types...>) {
    return [](auto&& f) {
        using swallow = int[];
        (void) swallow { 0, (void(f(tag<Types>{})), 0)... };
    };
}

这适用于 gcc,但在 visual studio 2015 中会产生以下错误:

main.cpp(19): error C3546: '...': there are no parameter packs available to expand

main.cpp(48): note: see reference to function template instantiation 'auto for_each::<lambda_9a452bac795593df4639d6433fa242d3>::operator ()<main::<lambda_b7b233027d9428cb5ddc16c87ea59d21>>(main::<lambda_b7b233027d9428cb5ddc16c87ea59d21> &&) const' being compiled

main.cpp(18): error C3520: 'Types': parameter pack must be expanded in this context

main.cpp(18): error C2672: 'operator __surrogate_func': no matching overloaded function found

main.cpp(18): error C2893: Failed to specialize function template 'auto main::<lambda_b7b233027d9428cb5ddc16c87ea59d21>::operator ()(_T1) const'

main.cpp(18): note: With the following template arguments:

main.cpp(18): note: '_T1=tag<Types>'

当符号 ... 未绑定(bind)到参数包(?)时,视觉编译器似乎无法扩展

有没有办法解决这个问题?

这是生成错误的最小示例:

#include <iostream>
#include <string>

template<typename... > struct type_list {};

template<typename T>
struct tag { using type = T; };

template<typename... Types>
auto for_each(type_list<Types...>) {
    return [](auto&& f) {
        using swallow = int[];
        (void) swallow { 0, (void(f(tag<Types>{})), 0)... };
    };
}

struct A {
    static std::string get_type_name() { return { "A" }; }
};

struct AA : A {
    static std::string get_type_name() { return { "AA" }; }
};

int main() {
    for_each(type_list<A, AA>{}) (
        [&](auto t) {
            using B = typename decltype(t)::type;
            std::cout << B::get_type_name() << std::endl;
        }
    );

    return 0;
}

最佳答案

我最终用结构替换了 for_each 函数:

template<typename T> struct for_each {};

template<typename... Types>
struct for_each<type_list<Types...>> {
    template<typename F>
    for_each(F f) {
        using swallow = int[];
        (void) swallow { 0, (f(tag<Types>{}), 0)... };
    }
};

稍微修改一下用法:

int main() {
    for_each<type_list<A, AA>>{
        [&](auto t) {
            using B = typename decltype(t)::type;
            std::cout << B::get_type_name() << std::endl;
        }
    };

    return 0;
}

关于c++ - 使用 Visual Studio 2015 : error C3546 在 lambda 中扩展参数包,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39425473/

相关文章:

c++ - 使用 gtest 1.6 : how to check what is printed out? 进行单元测试

c++ - 专业类中的模板别名

c++ - 错误 C3861 : 'execute_assert' : identifier not found

c++ - 散列多态类型的正确方法

c++ - 如何创建双 RowMajor 的动态大小的 Eigen::Matrix?

c++ - 如果需要参数包,请使用 SFINAE 专门化类(class)

c++ - OpenGL C++鼠标光线采摘glm :unproject

c++ - Dijkstra 算法 C++ 输出不正确

c++ - std::string length() 函数如何工作?

c++ - 如何使子控件处理父 CView 的加速器命令