我正在编写一个将声明作为其单个参数的宏。是否可以在宏内部推断声明的类型而不将单个参数拆分为单独的类型和标识符参数?
#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)。
最佳答案
如果您的静态断言消息真的那么简单 "!"
1,我建议您放弃预处理器。让类型系统为你工作:
namespace detail {
template<typename T>
struct check_declared_type {
using type = T;
static_assert(sizeof(type) == 4, "!");
};
}
template<typename T>
using M = typename detail::check_declared_type<T>::type;
// .. Later
int main() {
M<int> i;
M<double> d{3.14};
M<std::string> s{"Hello, world!"};
}
<子> 1 - 具体来说,如果您不需要预处理器为您对任何内容进行字符串化。
关于c++ - 推断声明的类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47014565/