【问题标题】:Get enumeration type from enumerator [duplicate]从枚举器获取枚举类型[重复]
【发布时间】:2016-08-04 16:06:08
【问题描述】:

假设我有这样的代码:

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

有没有办法减少使用现场的“重复”? IE。我不能从枚举器“Foo_A”等中推断出枚举类型“Foo”并以某种方式在上面的模板代码中使用它吗?枚举类在这里有帮助吗?

【问题讨论】:

  • 这段代码看起来像是解决某些问题的方法。有什么问题?

标签: c++ templates enums


【解决方案1】:

您的问题的答案是,目前没有办法做到这一点。你所面临的被称为template &lt;typename T, T t&gt; 成语。事实上,如果你用谷歌搜索,你会发现将近 75,000 次点击,而且没有解决方法。你必须像你一样专精。


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

  • N3405 提议允许template &lt;typename T t&gt; 其中T 是类型,t 是值,只有一个值作为模板参数传递
  • N3601 建议 template &lt;typename T, T t&gt; 是一种特殊情况,编译器将只接受一个值作为模板参数,并从中推断出 Tt
  • N4469 提议允许关键字auto 指定一个元参数:template &lt;auto t&gt; 这样一个值可以作为模板参数t 传递,并且它的类型被推导出来

在 5 月 4 日的 Lenexa 会议上,N4469 终于在标准委员会会议上获得了鼓励和修改请求:http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2015/n4539.html#9

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

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

P0127R2 专注于在工作草案的非概念部分中完全指定习语更改,因为尚不清楚概念是否将包含在 C++17 中。此修订版于 2016 年 6 月 23 日被 C++17 标准接受:http://developerblog.redhat.com/2016/07/13/red-hat-iso-c-standards-meeting-june-2016-core-language/

因此随着 C++17 的到来,您将能够处理 template &lt;typename T, T t&gt; 成语并使用:

template <auto t>
struct tpl{
    tpl(){ cout << typeid(decltype(t)).name() << ": " << t << endl; }
};

【讨论】:

  • 如果有人好奇的话,Visual Studio 使用type_info::raw_name() 来输出损坏的名称,这类似于 GCC 为type_info::name() 输出的名称。
  • 这是否意味着模板类型可能重载,f&lt;int&gt;() 调用与f&lt;bool&gt;() 不同的函数?
  • @JimV 你在说的是专业化(现在有可能。)这个问题是关于template &lt;typename T, T t&gt; 的成语。其中我必须调用tpl&lt;int, 13&gt;,即使13 显然是int。 N4469 试图让我们调用tpl&lt;13&gt; 并能够将其用作both 类型 值模板参数。
  • @JonathanMee:“但这取决于将概念合并到标准中”不,它没有。 It's going into C++17。他们所做的是编写附加措辞来解释此功能与概念之间的交互。
  • @NicolBolas 谢谢,我已经编辑了更新。我真的很兴奋,这会成功!
猜你喜欢
  • 2017-01-14
  • 1970-01-01
  • 2012-12-28
  • 1970-01-01
  • 2018-04-05
  • 2012-09-16
  • 2011-02-16
  • 1970-01-01
  • 2018-10-18
相关资源
最近更新 更多