使用 #pragma message() 打印编译期间 #define 的完整评估结果
Print fully evaluated result of #define during compilation using #pragma message()
我有一个关于使用 #pragma 消息打印 #defines 评估值的快速问题。我在Visual Studio 2008中使用msvc++。
下面是一个简化的示例:
#define __STR2__(x) #x
#define __STR1__(x) __STR2__(x)
#define WIDTH 10
#define HEIGHT 10
#define AREA (WIDTH * HEIGHT)
#pragma message("Area is: " __STR1__(AREA))
现在当我编译时,我得到以下输出:
>Area is: (10 * 10)
这不是我想要的。有没有办法打印出 #define 表达式的计算,以便我得到:
>Area is: 100
在编译期间。也许这是不可能的。最终,我希望能够在评估值太大时导致编译器错误。即
#if(AREA > 1000)
#pragma message(__ERROR__)
#endif
我的一些 #defines 使用sizeof()
我相信在评估条件时本身会导致问题 - 但这对未来来说是一个问题!
我看了下面的帖子如何在 gcc 中编译时显示 #define 的值,只要#define
定义为值而不是其他 #defines 的串联,就可以了。
预处理器不会为你做数学运算,它只能以文本方式替换标记和扩展宏。
如果你想在编译期间计算该值,你应该选择constexpr
(http://en.cppreference.com/w/cpp/language/constexpr,更准确地说,这将提示编译器在编译时计算它(
#include <iostream>
#define WIDTH 10
#define HEIGHT 10
template<int a, int b>
constexpr int getArea() {
static_assert(a*b < 1000, "Area is too big");
return a*b;
}
const int area = getArea<WIDTH, HEIGHT>();
int main(void) {
std::cout << area;
}
例
如果面积太大,static_assert将检查该区域。
预编译器可以在#if
语句中执行有限的数学运算。这可能足以满足您的需求:
#define WIDTH 10
#define HEIGHT 10
#define AREA (WIDTH * HEIGHT)
#if AREA > 1000
#error Oh bad, oh bad, oh bad
#endif
对于更复杂的数学,我会支持Marco A.所说的话,但你不需要在模板或其他任何东西中使用它。你可以把它和你所有的#define
一起放上去,例如:
#define WIDTH 10
#define HEIGHT 10
#define AREA (WIDTH * HEIGHT)
#define __ERROR__ "Oh bad, oh bad, oh bad"
static_assert(AREA < 1000, __ERROR__);
甚至更简单:static_assert(WIDTH * HEIGHT < 1000, "Oh bad, oh bad, oh bad");
相关文章:
- 为什么"do while"循环不断退出,即使条件计算结果为 false?
- valgrind-hellgrind与泄漏检查的结果不同
- 用C++20 fmt限制结果的总大小
- 如何返回一个类的两个对象相加的结果
- 使用QProcess执行命令,并将结果存储在QStringList中
- 如果我std::dynamic_pointer_cast并且底层dynamic_cast的结果为null,那么返回的sh
- 在没有定义返回类型的函数中返回布尔值,并将结果保存在无错误的char编译中-为什么
- 序列化,没有库的整数,得到奇怪的结果
- 使用取消引用的指针的多态性会产生意外的结果.为什么?
- 在更改for循环的第三部分后,未使用for循环结果
- 使用++运算符会导致意外的结果
- 为什么在逗号分隔符上下文中将预增量的结果强制转换为void
- C++Brute Force攻击函数不会返回结果
- 与C代码相比,为什么C++代码不需要"#define _POSIX_C_SOURCE 200809L"?
- 你好。。。id_public变量不应该给出结果为 81 和 86 吗?为什么它为两个派生类占用不同的内存位置?
- 算术运算的结果类似于:C浮点变量中的1/3
- 为什么一个简单的C++程序会有错误的结果?是 #define 引起的吗?
- 是否可以为 #define 分配定义的结果?
- 使用 #pragma message() 打印编译期间 #define 的完整评估结果
- 使用#define时奇怪的mod操作符(%)结果