编译时enum-string-int对

时间:2019-03-16 22:51:21

标签: c++ templates enums c++14 preprocessor

有没有一种方法可以在编译时使用指向字符串数组的索引来创建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) { /* ... */ }

我将如何去做?如果这不可能,还有另一种方法可以完成同一件事吗?

1 个答案:

答案 0 :(得分:2)

执行此操作的一种常见方法是将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 ++源代码。