[英]Compile-time check that a variable is signed/unsigned
I'm trying to come up with some compile-time ways to check if a certain variable is signed or unsigned. 我正在尝试提出一些编译时方法来检查某个变量是带符号的还是无符号的。 Actually, I was using the following macro for quite some time to check for a signed variable: 实际上,我花了很长时间使用以下宏来检查带符号的变量:
#ifdef _DEBUG
#define CHECK_SIGNED(v) if((v) == -(v)){}
#else
#define CHECK_SIGNED(v)
#endif
and then the following will pass it: 然后以下将通过它:
INT rr = 0;
CHECK_SIGNED(rr);
while the following: 而以下:
UINT rr = 0;
CHECK_SIGNED(rr);
will generate a compile-time error: 将产生一个编译时错误:
error C4146: unary minus operator applied to unsigned type, result still unsigned 错误C4146:一元减运算符应用于无符号类型,结果仍为无符号
So now I am trying to come up with a similar check for unsigned
variable. 因此,现在我试图为unsigned
变量提出类似的检查。 Any suggestions? 有什么建议么?
PS. PS。 Although I'm using VS 2017
it'd be nice to make it backwards compatible with older C++ standards. 尽管我使用的是VS 2017
但最好使其与旧的C ++标准向后兼容。
Could use something like this : 可以使用这样的东西:
static_assert(std::is_signed<decltype(rr)>::value, "Not signed number");
and the sister version std::is_unsigned
和姐妹版本std::is_unsigned
Also, those are not very difficult to implement on your own for supporting old compilers. 此外,对于支持旧的编译器,要靠自己实现并不是很困难。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.