创建从C ++宏字符串列表和一个枚举列表 [英] Creating a string list and an enum list from a C++ macro
问题描述
为了使我的code更短,更容易改变我要替换类似
In order to make my code shorter and easier to change I want to replace something like
enum{ E_AAA, E_BBB, E_CCC };
static const char *strings{"AAA", "BBB", "CCC" };
通过宏,像INIT(AAA,BBB,CCC);但是当我尝试做带有可变参数的宏和字符串化我得到一个错误的参数不声明。
With a macro, like INIT(AAA, BBB, CCC); but when I try doing a macro with variable arguments, and stringification I get an error as the arguments are not declared.
这是如何做到这一点任何想法?
Any idea on how to do this?
推荐答案
下面一个解决方案,我学到了前几天。在简单版本出席你的问题是:
Here a solution I learned a few days ago. The simplified version that attends your question is:
#define ENUM_MACRO(name, v1, v2, v3, v4, v5, v6, v7)\
enum name { v1, v2, v3, v4, v5, v6, v7};\
const char *name##Strings[] = { #v1, #v2, #v3, #v4, #v5, #v6, #v7};
ENUM_MACRO(Week, Sun, Mon, Tue, Wed, Thu, Fri, Sat);
但你可以有一个改进版本,以函数调用,就像这样:
#define ENUM_MACRO(name, v1, v2, v3, v4, v5, v6, v7)\
enum name { v1, v2, v3, v4, v5, v6, v7};\
const char *name##Strings[] = { #v1, #v2, #v3, #v4, #v5, #v6, #v7};\
const char *name##ToString(value) { return name##Strings[value]; }
ENUM_MACRO(Week, Sun, Mon, Tue, Wed, Thu, Fri, Sat);
这将成长为:
enum Week { Sun, Mon, Tue, Wed, Thu, Fri, Sat};
const char *WeekStrings[] = { "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"};
const char *WeekToString(value) { return WeekStrings[value]; };
您甚至可以使用偏移作为第一要素,像这样的:
You can even use an offset for the first element, like this one:
#define ENUM_MACRO(name, offset, v1, v2, v3, v4, v5, v6, v7)\
enum name { v1 = offset, v2, v3, v4, v5, v6, v7};\
const char *name##Strings[] = { #v1, #v2, #v3, #v4, #v5, #v6, #v7};\
const char *name##ToString(value) { return name##Strings[value - offset ]; }
ENUM_MACRO(Week, 1, Sun, Mon, Tue, Wed, Thu, Fri, Sat);
我希望这有助于。
I hope this helps.
保重,
贝乔
参考:
<一个href=\"http://stackoverflow.com/questions/5439174/print-the-month-corresponding-to-appropriate-input/\">Print本月问题,由库什,丹尼Varod答案
Print the month question, by Kush, answer by Danny Varod
这篇关于创建从C ++宏字符串列表和一个枚举列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!