繁体   English   中英

C ++中的枚举数组

[英]Arrays in enums in C++

目前,我的C ++代码是:

constexpr struct my_codes {
    std::array<int, other_class1::static_constans1> num1 = {{0, 1, 2, 3, 4, 5, 6}};
    std::array<int, other_class2::staric_constans2> num2 = {{7, 8, 9, 10, 11, 12, 13, 14}};
    int num3 = 15;
} my_codes;

显然,我对此感到难过,而且它一发不可收拾(我输入了前100个数字)。 可悲的是,这些枚举是非法的:

enum my_codes {
    num1[other_class1::static_constans1], 
    num2[other_class2::staric_constans2], 
    num3
};
enum my_codes {num1[7], num2[8], num3};

我可以通过一些魔术来枚举数组吗? 我可以使用任何宏吗? 一些递归模板?

编辑:我会像这样使用它:

enum my_codes {num1[7], num2[8], num[3]};
if (some_int == my_codes::num2[3]) do_somethig();

枚举将具有以下值:

my_codes::num1[0] == 0
my_codes::num1[1] == 1
...
my_codes::num1[6] == 6
my_codes::num2[0] == 7
my_codes::num2[1] == 8
...
my_codes::num2[7] == 14
my_codes::num3    == 15

由于常量是连续的,因此不需要数组-范围检查操作就足够了。 也就是说,由于num1包含[0, 7) num1 [0, 7)num2包含[7, 15) num2 [7, 15) ,因此您的结构可以表示为

 constexpr struct my_codes {
     std::array<int,4> num = {{0,7,14,15}}
 } mycodes;

 constexpr int getIndex(int i, int offset = 0) {
    return (offset==3 || i < mycodes.num[offset+1]) ?
    offset :
    getIndex(i, offset+1) ;
 }

这只是通过constexpr数组编写线性搜索的递归方法。 生成第i个范围甚至更简单,仅从num[i]num[i+1]

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM