GCC constexpr 允许添加但不允许按位或地址
GCC constexpr allows add but not bitwise-or with address
考虑这段代码:
#include <cstdint>
static int x = 0;
const uintptr_t arithmetic()
{
static constexpr uintptr_t result = ((uintptr_t)&x) + 1u;
return result;
}
const uintptr_t bitwise()
{
static constexpr uintptr_t result = ((uintptr_t)&x) | 1u;
return result;
}
GCC(所有版本 4-9)编译 arithmetic()
很好,但拒绝 bitwise()
:
<source>: In function 'const uintptr_t bitwise()':
<source>:13:57: error: '(((uintptr_t)(& x)) | 1)' is not a constant expression
13 | static constexpr uintptr_t result = ((uintptr_t)&x) | 1u;
| ~~~~~~~~~~~~~~~~^~~~
为什么?请注意,按位或在其他 constexpr 用例中工作正常,但在这个用例中不行。
您根本不能在常量表达式中使用 reinterpret_cast
(或执行一个的 C 风格转换)。 GCC 要么有一个强制执行该错误的错误,要么试图帮助支持一些 +
而不是 |
相关的实际用例。
考虑这段代码:
#include <cstdint>
static int x = 0;
const uintptr_t arithmetic()
{
static constexpr uintptr_t result = ((uintptr_t)&x) + 1u;
return result;
}
const uintptr_t bitwise()
{
static constexpr uintptr_t result = ((uintptr_t)&x) | 1u;
return result;
}
GCC(所有版本 4-9)编译 arithmetic()
很好,但拒绝 bitwise()
:
<source>: In function 'const uintptr_t bitwise()':
<source>:13:57: error: '(((uintptr_t)(& x)) | 1)' is not a constant expression
13 | static constexpr uintptr_t result = ((uintptr_t)&x) | 1u;
| ~~~~~~~~~~~~~~~~^~~~
为什么?请注意,按位或在其他 constexpr 用例中工作正常,但在这个用例中不行。
您根本不能在常量表达式中使用 reinterpret_cast
(或执行一个的 C 风格转换)。 GCC 要么有一个强制执行该错误的错误,要么试图帮助支持一些 +
而不是 |
相关的实际用例。