编译时枚举器的顺序 [英] Sequence of enumerators at compile time

查看:236
本文介绍了编译时枚举器的顺序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给定一个C ++ 11枚举类,是否有一些模板或其他构造在编译时迭代,在所有枚举器的集合?可以定义一个模板,例如。使用该枚举类型的所有可能值来初始化数组?

解决方案

一种替代技术是使用预处理器。 / p>

  #define ITERATE_MY_ENUM(_)\ 
_(A,)\
_ = 3)\
_(C,)\
_(D,= 10)

枚举MyEnum {
#define DEFINE_ENUM_VALUE键值,

ITERATE_MY_ENUM(DEFINE_ENUM_VALUE)

#undef DEFINE_ENUM_VALUE
};

void foo(){
MyEnum arr [] = {
#define IN_ARRAY_VALUE(键,值)键,

ITERATE_MY_ENUM(IN_ARRAY_VALUE)

#udnef IN_ARRAY_VALUE
};有些人可能会认为它丑陋,但它仍然保持代码 http://en.wikipedia.org/wiki/Don%27t_repeat_yourself =nofollow> DRY


Given a C++11 enum class, is there some templating or other construct to iterate, at compile-time, over the set of all enumerators? Could one define a template to e.g. initialize an array with all possible values of that enum type?

解决方案

One alternative technique is to resort to the pre-processor.

#define ITERATE_MY_ENUM(_) \
  _(A,) \
  _(B, =3) \
  _(C,) \
  _(D, =10)

enum MyEnum {
  #define DEFINE_ENUM_VALUE(key, value) key value,

  ITERATE_MY_ENUM(DEFINE_ENUM_VALUE)

  #undef DEFINE_ENUM_VALUE
};

void foo() {
  MyEnum arr[] = {
    #define IN_ARRAY_VALUE(key, value) key,

    ITERATE_MY_ENUM(IN_ARRAY_VALUE)

    #udnef IN_ARRAY_VALUE
  };
}

Some may consider it ugly, but it still keeps the code DRY.

这篇关于编译时枚举器的顺序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆