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

如何将枚举类的范围for循环打印逻辑封装到函数中?

实现独立函数打印枚举类对应的字符串数组

这里提供两种可行的实现方案,均基于C++11及以上标准:

方案1:模板函数推导数组长度

直接通过模板推导字符串数组的大小,编写通用打印函数:

#include <iostream>

#define DEFINE_ENUM_CLASS(Name, ...) \
enum class Name { __VA_ARGS__ }; \
constexpr const char* Name##Strings[] = { #__VA_ARGS__ };

// 独立打印函数:通过模板参数自动推导数组元素个数
template <size_t ArraySize>
void printEnumStrings(const char* const (&enumStrings)[ArraySize]) {
    for (const char* name : enumStrings) {
        std::cout << name << '\n';
    }
}

int main()
{
    DEFINE_ENUM_CLASS(Color, Red, Green, Blue);
    DEFINE_ENUM_CLASS(Bolor, Blue, Cyan, Green);

    printEnumStrings(ColorStrings);
    printEnumStrings(BolorStrings);
}

说明

  • 函数通过数组引用接收参数,模板参数ArraySize会由编译器自动推导数组的元素数量,范围for循环可正常遍历整个数组。
  • 保留原宏定义,无需修改枚举类生成逻辑,直接复用现有字符串数组。

方案2:绑定枚举类型与字符串数组

修改宏添加辅助函数,让打印函数可直接通过枚举类型获取对应字符串数组,调用更直观:

#include <iostream>

#define DEFINE_ENUM_CLASS(Name, ...) \
enum class Name { __VA_ARGS__ }; \
constexpr const char* Name##Strings[] = { #__VA_ARGS__ }; \
// 辅助函数:通过枚举类型实例返回对应的字符串数组
constexpr auto getEnumStrings(Name) { return Name##Strings; }

// 模板打印函数:根据枚举类型自动获取字符串数组
template <typename EnumType>
void printEnumStrings() {
    constexpr auto enumStrings = getEnumStrings(EnumType{});
    for (const char* name : enumStrings) {
        std::cout << name << '\n';
    }
}

int main()
{
    DEFINE_ENUM_CLASS(Color, Red, Green, Blue);
    DEFINE_ENUM_CLASS(Bolor, Blue, Cyan, Green);

    printEnumStrings<Color>();
    printEnumStrings<Bolor>();
}

说明

  • 宏新增getEnumStrings函数,接收枚举类型的临时实例(默认构造),返回对应枚举的字符串数组。
  • 打印函数为模板函数,调用时只需指定枚举类型(如printEnumStrings<Color>()),无需直接引用ColorStrings变量,代码可读性更强。

内容的提问来源于stack exchange,提问作者sick nasty

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.18 07:17:45