有没有办法在编译时用字符串数组的索引创建一个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++ 源代码。
关于c++ - 编译时枚举字符串整数对,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55202286/