加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c – 使用Visual Studio 2015在lambda中扩展参数包:错误C3546

发布时间:2020-12-16 06:52:29 所属栏目:百科 来源:网络整理
导读:在 this question之后,我尝试编译以下代码: templatetypename... Typesauto for_each(type_listTypes...) { return [](auto f) { using swallow = int[]; (void) swallow { 0,(void(f(tagTypes{})),0)... }; };} 这适用于gcc,但使用visual studio 2015生成
在 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生成以下错误:

06001

当符号…没有绑定到参数包(?)时,可视化编译器看起来失败了

有办法解决问题吗?

以下是生成错误的最小示例:

#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,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;
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读