使用constexpr编译时出错

Error compilation with constexpr

本文关键字:出错 编译 constexpr 使用      更新时间:2023-10-16

我正在尝试编译这段代码:

enum class Order : char
{
    Little,
    Big
};
constexpr Order get_order() {
    uint16_t x = 1;
    return *((uint8_t *) &x) == 0 ? Order::Big : Order::Little;
}

我用-std=c++14标记,但我得到这个错误:

在函数constexpr byteorder::Order byteorder::get_order()中:/home/user/dev/c++/render/include/byteorder.h:19:1:错误:constexpr函数' constexpr byteorder::Order byteorder::get_order() '不是return-statement

如果c++14允许在constexpr函数中使用局部变量,这怎么可能发生呢?

clang说:

test.cpp:9:17: error: constexpr function never produces a constant expression
    [-Winvalid-constexpr]
constexpr Order get_order() {
                ^
test.cpp:11:14: note: cast that performs the conversions of a reinterpret_cast
is not allowed in a constant expression
    return *((uint8_t *) &x) == 0 ? Order::Big : Order::Little;
             ^
1 error generated.

从这里的GCC标准实现页面来看,这似乎只适用于GCC版本5及以上。

constexpr说明符声明可以在编译时计算函数或变量的值。

你取了一个局部变量的地址(在运行时赋值),这意味着不可能在编译时对该表达式求值。

编辑:

尽管如此,对于可能导致未定义行为的表达式,我们认为其不符合constexpr要求的核心常数表达式和函数是受限制的。指针解引用可能属于这一类,或者使用reinterpret_cast进行强制转换,这与传统的强制转换类似。