【发布时间】:2017-10-30 11:51:04
【问题描述】:
我正在编写一个将声明作为其单个参数的宏。是否可以在宏内推断声明的类型,而不将单个参数拆分为单独的 type 和 identifier 参数?
#define M(declaration) \
declaration; \
static_assert(sizeof(/* deduce type of 'declaration' */) == 4, "!")
M(int i);
M(double d{3.14});
M(std::string s{"Hello, world!"});
以下实现可行,但感觉不太友好(imo):
#define M(type, identifier) \
type identifier; \
static_assert(sizeof(type) == 4, "!")
M(int, i);
M(double, d{3.14});
M(std::string, s{"Hello, world!"});
如果可能,我更愿意将声明作为单个参数。
相关问题: Macro to get the type of an expression;但我未能让该代码在我的示例中工作(编译器错误:expected nested-name-specifier)。
【问题讨论】:
-
你打算让静态断言最后打印标识符吗?因为如果没有,还有一个解决方案也可以抛弃预处理器。
-
@StoryTeller 我不一定需要标识符。但如果你能想到多种解决方案,我会对它们都感兴趣。
标签: c++ macros type-deduction