问题描述
为了使我的代码更短更容易更改,我想替换类似的东西
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.
你知道怎么做吗?
推荐答案
这是我前几天学到的一个解决方案.处理您的问题的简化版是:
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);
但您可以使用函数调用的改进版本,如下所示:
But you can have an improved version, with a function call, like this:
#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);
我希望这会有所帮助.
保重,贝科
参考:
打印月份问题,由 Kush 回答丹尼·瓦罗德
Print the month question, by Kush, answer by Danny Varod
这篇关于从 C++ 宏创建字符串列表和枚举列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!