编译时枚举字符串整数对

Compile-time enum-string-int pair

有没有办法在编译时使用字符串数组的索引创建 enum

类似于:

// Programmer types this in:
SOME_MACRO(PEAR,"a pear");
SOME_MACRO(APPLE,"an apple");
SOME_MACRO(ORANGE,"an orange");
// ...

// Result after pre-processing and "compiling"

// String array
const char* myarray[] = { "a pear", "an apple", "an orange", /* ... */ };

// Enum
enum myenum
{
    PEAR = 1,
    APPLE = 2,
    ORANGE = 3,
    // ...
}

我的最终目标是能够在编译时使用枚举值查找字符串,反之亦然:

myenum toEnum(const char* str) { /* ... */ }
const char* toString(myenum e) { /* ... */ }

我该怎么做?如果这不可能,是否有其他方法可以完成同样的事情?

一个常用的方法是将 SOME_MACRO 调用列表放入一个单独的头文件中,然后 #include 这个文件两次,每次都不同地定义 SOME_MACRO 。沿着这些线的东西:

#define SOME_MACRO(name, text) text,
const char* myarray[] = {
  #include "mylist.h"
};
#undef SOME_MACRO

#define SOME_MACRO(name, text) name,
enum myenum
{
  #include "mylist.h"
};
#undef SOME_MACRO

另一种常见的方法是用某种脚本语言(例如 Python)定义数据,然后编写一个生成 C++ 源代码的简单脚本。