我在我的代码中使用宏来定义简单的变量(类似这样):
#define foobar 1
//...
barfoo(foobar);
为了防止错误,我想通过验证输入来确保 foobar
是一个数字。 foobar
应该始终是一个数字,因此它可以非常简单。
显然,预处理器不处理数学,因此任何通过算术产生某种类型错误的希望都落空了。
我想出于这个原因,常量确实更好,但我正在尝试使用所有宏,以便它在我拥有的配置文件中保持一致(有些需要宏)。正则表达式可能是一个不错的解决方法,但 GCC 似乎不支持 [with macros] 这个(加上, 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");
关于c++ - 我可以验证预处理器宏以确保它是一个数字吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27204622/