G++ 和 STD 11 有 constexpr 的问题

G++ and STD 11 has problems with constexpr

我正在尝试在 g++ 和 clang++ 中使用相同的 constexpr,包括最新版本和参数“-std=c++11”。 Clang 编译没有问题,但是 G++ return 错误。 来源是:

#include <functional>

enum class LoggerLevel : unsigned {
    NO_LEVEL = 0,
    VERBOSE = 1 << 0,
    DEBUG = 1 << 1,
    INFO = 1 << 2,
    WARNING = 1 << 3,
    ERROR = 1 << 4,
    FATAL = 1 << 5,
    ALL_LEVELS = 0 | VERBOSE | DEBUG | INFO | WARNING | ERROR | FATAL,
};

constexpr LoggerLevel operator|(LoggerLevel lhs, LoggerLevel rhs) noexcept {
    return static_cast<LoggerLevel>(static_cast<unsigned>(lhs) | static_cast<unsigned>(rhs));
}

constexpr LoggerLevel& operator|=(LoggerLevel& lhs, LoggerLevel rhs) noexcept {
    return lhs = lhs | rhs;
}

int main()
{
    auto x = LoggerLevel::ALL_LEVELS;
    return 0;
}

错误是:

<source>: In function 'constexpr LoggerLevel& operator|=(LoggerLevel&, LoggerLevel)':

<source>:19:16: error: expression '(lhs = operator|(lhs, rhs))' is not a constant expression

     return lhs = lhs | rhs;

            ~~~~^~~~~~~~~~~

Compiler returned: 1

神螺栓示例:

https://godbolt.org/z/M6ERms

感谢您的帮助。

至少针对 C++14 之前的 C++14 标准进行编译,核心 constant expression 评估将 评估赋值或复合赋值您拥有的运算符:

return lhs = lhs | rhs;

C++11草案中的相关章节是5.19.2常量表达式(强调我的):

A conditional-expression is a core constant expression unless it involves one of the following as a potentially evaluated subexpression ...

  • an assignment or a compound assignment