gpt4 book ai didi

c++ - 在编译期间使用#pragma message() 打印#define 的完全评估结果

转载 作者:太空宇宙 更新时间:2023-11-04 11:26:41 30 4
gpt4 key购买 nike

我有一个关于使用#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(),我认为这在评估条件时本身会导致问题 - 但这是 future 的问题!

我查看了以下帖子 How do I show the value of a #define at compile time in gcc只要 #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;
}

Example

static_assert如果它太大,将对该区域进行检查。

关于c++ - 在编译期间使用#pragma message() 打印#define 的完全评估结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26424711/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com