問題描述
假設我們有一些命名的枚舉:
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)
};
這篇關于有沒有一種簡單的方法可以將 C++ 枚舉轉換為字符串?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!