【问题标题】:Arrays in enums in C++C ++中枚举中的数组
【发布时间】:2017-10-29 22:26:00
【问题描述】:

目前我的 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

【问题讨论】:

  • “显然我对此感到难过”……显然,但仍然……幽默,这有什么问题?
  • 可能有一种方法可以设置某些东西,以便您可以使用某些名称就好像有一个以这种方式定义的枚举。那么您希望使用这些的代码看起来如何?
  • 你能解释一下“枚举中的数组”对你意味着什么吗?
  • 您能否提供一些实际使用它的代码,以便我们知道您要做什么?
  • struct 和 enum 之间有什么联系?无法弄清楚您要做什么。也许值得解释......

标签: c++ arrays enums


【解决方案1】:

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

 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]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2010-11-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-10-16
    相关资源
    最近更新 更多