You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C++中遍历enum class(强类型枚举)的常用方法有哪些?

enum class 遍历通用方案

所有适用于普通enum(弱类型枚举)的标准遍历方法都无法直接用于enum class,核心原因是enum class不支持隐式类型转换为整数,你可以根据枚举的特性选择以下两种常用实现方案:

方案1:范围增量遍历(适合枚举值连续的场景)

如果你的enum class是按照整数连续递增赋值的(默认无自定义赋值的枚举就符合这个特性),可以通过添加边界枚举值配合类型转换实现遍历:

  • 第一步:在枚举定义末尾添加边界标记值
enum class Color {
    Red = 0,
    Green,
    Blue,
    kBegin = Red, // 枚举起始值
    kEnd = Blue + 1 // 枚举结束边界
};
  • 第二步:基础遍历写法
for (int i = static_cast<int>(Color::kBegin); i < static_cast<int>(Color::kEnd); i++) {
    Color current_color = static_cast<Color>(i);
    // 此处处理current_color对应的逻辑
}
  • 如果你希望使用更简洁的范围for语法,可以封装通用的枚举范围模板:
template <typename T>
class EnumRange {
public:
    class Iterator {
    public:
        explicit Iterator(int val) : m_val(val) {}
        T operator*() const { return static_cast<T>(m_val); }
        Iterator& operator++() {
            m_val++;
            return *this;
        }
        bool operator!=(const Iterator& other) const {
            return m_val != other.m_val;
        }
    private:
        int m_val;
    };

    EnumRange(T begin, T end) : m_begin(static_cast<int>(begin)), m_end(static_cast<int>(end)) {}
    Iterator begin() const { return Iterator(m_begin); }
    Iterator end() const { return Iterator(m_end); }
private:
    int m_begin;
    int m_end;
};

封装后遍历写法:

for (Color c : EnumRange(Color::kBegin, Color::kEnd)) {
    // 直接处理枚举值c即可
}

方案2:枚举值数组遍历(适合所有场景,优先推荐)

如果你的enum class存在自定义不连续赋值,或者不希望修改枚举定义,可以直接预定义枚举值数组实现遍历:

enum class Color {
    Red = 1,
    Green = 4,
    Blue = 7
};

// 预定义所有枚举值的常量数组
constexpr Color kAllColors[] = {Color::Red, Color::Green, Color::Blue};

遍历写法:

for (Color c : kAllColors) {
    // 直接处理枚举值c即可
}

该方案适配所有枚举场景,无需依赖枚举值的连续性,可读性和可维护性更高,仅需要在新增枚举值时同步更新数组内容。


内容的提问来源于stack exchange,提问作者Gabriel Staples

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.28 04:36:00