使用 constexpr 编译时出错

Error compilation with constexpr

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

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 标志来做,但我得到了那个错误:

In function ‘constexpr byteorder::Order byteorder::get_order()’: /home/user/dev/c++/render/include/byteorder.h:19:1: error: body of constexpr function ‘constexpr byteorder::Order byteorder::get_order()’ not a return-statement

看起来像c++11 !

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

Debian Jessie,gcc 4.9.2

The constexpr specifier declares that it is possible to evaluate the value of the function or variable at compile time.

您正在获取局部变量的地址(在运行时分配),这意味着无法在编译时评估该表达式。

编辑: 尽管如此,可能导致未定义行为的表达式被认为受限于核心常量表达式和函数,因为它似乎无法满足 constexpr 要求。指针取消引用可能属于此类或使用 reinterpret_cast 进行转换,这与传统转换一样。

从 GCC standard implementation page here 看来这仅适用于 GCC 版本 5 及更高版本。

有效 here using GCC 6.1.0

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.