【发布时间】:2014-04-06 09:15:42
【问题描述】:
我有一堆看起来像这样的枚举(如果您想知道,来自 libvirt 库):
enum whatever {
VAL_A = 1
VAL_B = 2
...
}
如何将这些转换为有意义的字符串?也就是说,VAL_A 具有状态含义“meaning_A”,VAL_B 具有状态含义“meaning_B”等等。在 php 或 perl 或 python 中,我会生成一个 key:val 对并在 O(1) 时间内返回结果。有没有一种有效的方法将这些映射到 C 中有意义的字符串?我正在考虑一个 switch 语句,但想知道更好的方法。
谢谢,
维克。
【问题讨论】:
-
有关相关问题,请参阅 X-Macros 和 SO 问题,例如 Counting preprocessor macros、Is it possible to modify this X-macro to build a struct which includes arrays 和 Displaying
#definevalues in C — 我怀疑还有其他问题,但我还没有重新发现它们。 -
C 和 python 一样好——至少如果你能找到一个很好的库来执行 key:val 转换。那么问题是,如果您想执行两次肮脏的黑客/宏,例如 #include "foo.bar" 两次,以使其看起来您只需要像
DIRTY_MACRO( 1,2,700,701,900);中那样输入一次值,这将产生两个 key:val 对和枚举。
标签: c data-structures hash enums