将数字附加到枚举以获得其他枚举

Appending a number to enum to get other enum

我想通过附加一个数字在 for 循环中获取枚举值,例如

enum example
{
Example_1,
Example_2,
Example_3,
.
.
.
Example_n
};
example x;
for (i = 0; i < n; i++
{x = Example_ + i; // if i = 5, I need Example_5
}

我想要 C++11 中的这个实现

如果您在枚举中有一个 Example_0,那么 Example_0 + 5 将为您提供一个等于 Example_5 的整数值。枚举只是整数。

所有这些假设您没有明确地为某个枚举常量赋值 - 那是另一回事了。

您不能将名称与数字连接起来以检索枚举名称和使用枚举值。

  • 有了连续的枚举,你可以使用简单的算术。

  • 您可以为您的枚举创建 operator++,通过开关解析:

    example operator++(example e)
    {
        switch (e) {
        case Example_1: return Example_2;
        case Example_2: return Example_3;
        case Example_3: return Example_4;
        // ...
        case Example_n: return Last;
        };
        throw std::runtime("value out of range");
    }
    

    等等,可能

    for (example e = Example_1: e != Last; ++e) {/*..*/}

  • 使用数组提供枚举列表:

    constexpr auto AllExamples() {
        constexpr std::array res{{Example_1,
                                  Example_2,
                                  /*..*/,
                                  Example_n}};
        return res;
    }
    

    允许:

    for (auto ex : AllExamples()) {/*..*/}
    f(AllExamples()[5]);
    
  • 如果你真的需要玩弄名字,也可以使用 map:

    std::map<std::string, example> ExamplesAsMap() {
        return {
            {"Example_1", Example_1},
            {"Example_2", Example_2},
            /*..*/
            {"Example_n", Example_n},
            {"Value_1", Value_1},
            {"Value_2", Value_2},
            /*..*/
            {"Value_n", Value_n}
            /**/
        };
    }
    

    然后

    const auto m = ExamplesAsMap();
    example x;
    for (int i = 0; i < n; i++) {
        x = m.at("Example_" + std::to_string(i));
        // ...
    }