有没有一种简单的方法可以将 C++ 枚举转换为字符串?

2021-12-05 00:00:00 string enums scripting c++

假设我们有一些命名的枚举:

Suppose we have some named enums:

enum MyEnum {
      FOO,
      BAR = 0x50
};

我用谷歌搜索的是一个脚本(任何语言),它扫描我项目中的所有标题并生成一个每个枚举一个函数的标题.

What I googled for is a script (any language) that scans all the headers in my project and generates a header with one function per enum.

char* enum_to_string(MyEnum t);

还有一个类似这样的实现:

And a implementation with something like this:

char* enum_to_string(MyEnum t){
      switch(t){
         case FOO:
            return "FOO";
         case BAR:
            return "BAR";
         default:
            return "INVALID ENUM";
      }
 }

问题在于 typedefed 枚举和未命名的 C 风格枚举.有人对此有所了解吗?

The gotcha is really with typedefed enums, and unnamed C style enums. Does anybody know something for this?

该解决方案不应修改我的源代码,生成的函数除外.枚举位于 API 中,因此使用目前提出的解决方案不是一种选择.

The solution should not modify my source, except for the generated functions. The enums are in an API, so using the solutions proposed until now is just not an option.

推荐答案

@hydroo: 没有额外的文件:

@hydroo: Without the extra file:

#define SOME_ENUM(DO) 
    DO(Foo) 
    DO(Bar) 
    DO(Baz)

#define MAKE_ENUM(VAR) VAR,
enum MetaSyntacticVariable{
    SOME_ENUM(MAKE_ENUM)
};

#define MAKE_STRINGS(VAR) #VAR,
const char* const MetaSyntacticVariableNames[] = {
    SOME_ENUM(MAKE_STRINGS)
};

相关文章