【发布时间】:2021-08-09 09:54:21
【问题描述】:
我有一个#define 生成一个枚举类和一个对应的输出操作符生成的枚举类。(见下文)
#define ENUM(N, T, N1, V1, N2, V2, N3, V3, N4, V4, N5, V5, N6, V6, N7, V7)\
enum class N : T {\
N1 = V1,\
N2 = V2,\
N3 = V3,\
N4 = V4,\
N5 = V5,\
N6 = V6,\
N7 = V7,\
};\
std::ostream &operator <<(std::ostream &os, const N val); /* declare function to avoid compiler warning */\
std::ostream &operator <<(std::ostream &os, const N val) {\
switch (val) {\
case N::N1:\
os << #N1;\
break;\
case N::N2:\
os << #N2;\
break;\
case N::N3:\
os << #N3;\
break;\
case N::N4:\
os << #N4;\
break;\
case N::N5:\
os << #N5;\
break;\
case N::N6:\
os << #N6;\
break;\
case N::N7:\
os << #N7;\
break;\
}\
if (sizeof(T) == 1) {\
os << '(' << static_cast<int>(val) << ')';\
} else {\
os << '(' << static_cast<T>(val) << ')';\
}\
return os;\
}
在这个例子中可以像这里一样使用:
#include <cstdlib>
#include <iostream>
#include <ostream>
ENUM(Weekdays, unsigned char, Monday, 10, Tuesday, 12, Wednesday, 14, Thursday, 16, Friday, 18, Saterday, 100, Sunday, 101)
int main(const int /*argc*/, const char *const /*argv*/[]) {
Weekdays test = Weekdays::Monday;
std::cout << test << std::endl;
std::cout << Weekdays::Tuesday << std::endl;
std::cout << Weekdays::Sunday << std::endl;
return EXIT_SUCCESS;
}
这里是生成的输出:
Monday(10)
Tuesday(12)
Sunday(101)
我的解决方案有一些限制:
- 每个枚举都需要一个初始化值
- 固定为 7 个枚举值
对于更通用的用法,我有两个问题。特别是第二个会极大地增加可用性。
这里有我的问题:
- 如何避免为每个枚举值定义一个初始化值?
(就像在真正的枚举中一样) - 有什么想法可以概括 #define 以处理任意数量的值?
我正在等待您的 cmets 对我的代码提出改进建议。
雷纳
【问题讨论】:
-
你在写 C++,那你为什么不用模板呢?
-
@Dai 使用模板将枚举转换为字符串相当晦涩。
-
可以用 X 宏来完成
-
@Dai 我对模板不是很熟悉。我不知道如何用模板实现这一点,也不知道如何用模板解决我的问题。如果可以,请告诉我们如何操作!
标签: c++ variadic define-syntax