c++ - 为每个枚举器添加代码

标签 c++ templates enums

我有一些像下面这样的任意枚举。

enum MyEnumWith2Items {
    Item1,
    Item2
};

enum MyEnumWith3Items {
    Item1,
    Item2,
    Item3
};

我想添加一些依赖于每个枚举器的代码。比如在每一个item对应的类中增加一个字段。

template<typename EnumType>
struct MyStruct {
    /* magic */
};

MyStruct<MyEnumWith2Items> a; // a has the fields i1 and i2, but not i3
MyStruct<MyEnumWith3Items> b; // b has i1, i2 and i3

这可能吗?
enum class 怎么样?
static 字段或方法或任何类型的代码怎么样?

类定义可以采用任何形式,我的例子只是一个例子。
我可以使用任何版本的 C++。

最佳答案

如果您对 myStruct 的静态成员感兴趣,使用 C++14(因此静态模板成员可用),您可以按如下方式定义 myStruct

template <typename E>
struct myStruct
 {
   template <E I>
   struct wrp
    { int value; };

   template <E I>
   static wrp<I> item;
 };

template <typename E>
template <E I>
myStruct<E>::wrp<I> myStruct<E>::item { 0 };

并给定以下枚举数

enum MyEnumWith2Items { Item1, Item2 };
enum MyEnumWith3Items { Item3, Item4, Item5 };

你可以写

int main ()
 {    
   myStruct<MyEnumWith2Items>::item<Item1>.value = 1;
   myStruct<MyEnumWith2Items>::item<Item2>.value = 2;

   myStruct<MyEnumWith3Items>::item<Item3>.value = 3;
   myStruct<MyEnumWith3Items>::item<Item4>.value = 4;
   myStruct<MyEnumWith3Items>::item<Item5>.value = 5;
 }

Pre C++14(以及 C++14 本身)您可以在模板方法中使用静态变量获得类似的结果;下面是一个完整的例子

#include <iostream>

enum MyEnumWith2Items { Item1, Item2 };
enum MyEnumWith3Items { Item3, Item4, Item5 };

template <typename E>
struct myStruct
 {
   template <E I>
   int & item ()
    { static int value = 0; return value; }
 };

int main ()
 {
   myStruct<MyEnumWith2Items>  e2;
   myStruct<MyEnumWith3Items>  e3;

   e2.item<Item1>() = 1;
   e2.item<Item2>() = 2;

   e3.item<Item3>() = 3;
   e3.item<Item4>() = 4;
   e3.item<Item5>() = 5;

   std::cout << "e2: " << e2.item<Item1>() << ", " << e2.item<Item2>() 
      << std::endl;                              // print e2: 1, 2
   std::cout << "e3: " << e3.item<Item3>() << ", " << e3.item<Item4>() 
      << ", " << e3.item<Item5>() << std::endl;  // print e3: 3, 4, 5
 }

关于c++ - 为每个枚举器添加代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44617605/

相关文章:

c++ - 是否有无限参数序列的模板?

c++ - 函数作为模板参数问题

java - 接口(interface)中的静态方法不起作用,如何从多个枚举中获取特定的枚举值?

c++ - 与观察者指针共享指针

c++ - 使用 pthread_create() 创建超过 1000 个线程

c++ - 是否可以从 unsigned char 数据类型函数向主函数返回一个整数?

c++ - 公开基类枚举而不用乏味地列出枚举数

c++ - 使用 boost 正则表达式时出现 shared_ptr 错误

javascript - 为什么 JQuery Growfield 插件为我的文本区域提供默认值 "111 111"?

Swift 2 if 具有关联值的枚举的大小写语法