Ano*_*uin 0 c++ validation macros c-preprocessor
我正在使用宏来定义代码中的简单变量(类似这样):
#define foobar 1
//...
barfoo(foobar);
Run Code Online (Sandbox Code Playgroud)
为了防止错误,我想foobar通过验证输入来确保是一个数字.foobar应该总是一个数字,所以它可以很简单.
显然,预处理器不处理数学,所以任何用算术生成某种类型错误的希望都会丢失.
我想常量因为这个原因确实更好,但我正在尝试使用所有宏,因此它在我拥有的配置文件中是一致的(有些确实需要宏).正则表达式可能是一个好的解决方法,但GCC似乎不支持[与宏]这个(加上,http://xkcd.com/1171/).
在C++ 11中,有类型特征和静态断言可以满足您的目的:
#include <type_traits>
#define foo 1
// #define foo "bar" // will lead to a compiler error containing the message "foo is not int"
static_assert(std::is_integral<decltype(foo)>::value, "foo is not int");
Run Code Online (Sandbox Code Playgroud)