C++ 从枚举器获取枚举类型

C++ 从枚举器获取枚举类型,c++,templates,enums,C++,Templates,Enums,假设我有这样的代码: #include <cstdio> enum Foo { Foo_A, Foo_B }; enum Bar { Bar_A, Bar_B }; template<typename enumeration, int enumerator> struct tpl; template<int enumerator> struct tpl<Foo, enumerator> { tpl() { printf("Foo: %

假设我有这样的代码:

#include <cstdio>

enum Foo { Foo_A, Foo_B };
enum Bar { Bar_A, Bar_B };

template<typename enumeration, int enumerator>
struct tpl;

template<int enumerator>
struct tpl<Foo, enumerator>
{
    tpl() { printf("Foo: %d\n", enumerator); }
};

template<int enumerator>
struct tpl<Bar, enumerator>
{
    tpl() { printf("Bar: %d\n", enumerator); }
};

int main()
{
    tpl<Foo, Foo_A> foo_a;
    tpl<Foo, Foo_B> foo_b;
    tpl<Bar, Bar_A> bar_a;
    tpl<Bar, Bar_B> bar_b;
    return 0;
};
#包括
enum Foo{Foo_A,Foo_B};
枚举条{Bar_A,Bar_B};
模板
结构化第三方物流;
模板
结构化第三方物流
{
tpl(){printf(“Foo:%d\n”,枚举器);}
};
模板
结构化第三方物流
{
tpl(){printf(“条:%d\n”,枚举器);}
};
int main()
{
第三方物流福华;
第三方物流有限公司;
第三方物流巴鲁阿;
第三方物流有限公司;
返回0;
};

有没有办法减少使用站点的“重复”?也就是说,我不能从枚举器“Foo_A”等推断枚举类型“Foo”,并在上面的模板代码中使用它吗?enum类在这里有用吗?

您的问题的答案是,不,目前没有一种方法可以做到这一点。你所面临的就是所谓的
模板
习惯用法。事实上,如果你用谷歌搜索它,你会发现近75000次点击,而且没有解决办法。你必须尽可能地专攻


但好消息即将出现。在过去十年中,已多次向标准委员会提出这一建议:

  • 提出了
    template
    的容差,其中
    T
    是类型,
    T
    是值,只有一个值作为模板参数传递
  • 建议将
    template
    作为一种特殊情况,编译器只接受一个值作为模板参数,并由此推断
    T
    T
  • 建议允许关键字
    auto
    指定元参数:
    模板

    第一次修订于2015年9月25日提交

    2016年3月4日提交了后续修订:建议对概念工作草案部分进行编辑

    重点是在工作草案的非概念部分中完全指定惯用语更改,因为不清楚概念是否会包含在C++17中。此版本于2016年6月23日被纳入C++17标准:

    因此,随着C++17的到来,您将能够处理
    模板
    习惯用法并使用:

    template <auto t>
    struct tpl{
        tpl(){ cout << typeid(decltype(t)).name() << ": " << t << endl; }
    };
    
    模板
    结构化第三方物流{
    
    tpl(){cout此代码看起来像是某个问题的解决方案。问题是什么?如果有人好奇,Visual Studio会使用
    type\u info::raw\u name()
    输出损坏的名称,这类似于GCC为
    type\u info::name()
    输出的名称。这是否意味着可以使用
    f()重载模板类型
    调用另一个函数
    f()
    ?@JimV您所说的是专门化(现在这是可能的)这个问题是关于
    template
    的习惯用法。我必须调用
    tpl
    ,尽管
    13
    显然是一个
    int
    。N4469试图允许我们调用
    tpl
    ,并能够将其用作类型和值模板参数。@JonathanMee:“但这取决于将概念合并到标准中”不,不是这样。他们所做的是写额外的文字来解释此功能和概念之间的交互作用。@Nicolas感谢,我已经编辑了更新。我真的很兴奋这会成功!