相关疑难解决方法(0)

可以在 constexpr 函数中声明静态局部变量吗?

可以在函数中使用static局部变量吗?constexpr例如:

#include <string_view>
#include <utility>

enum class axis {
    x, y, z
};

constexpr std::string_view axis_name(axis a) {
    // use static constexpr to avoid putting the table onto the stack
    static constexpr std::string_view names[] {
        "x", "y", "z"
    };
    return names[std::to_underlying(a)];
}

constexpr auto x_name = axis_name(axis::x);
Run Code Online (Sandbox Code Playgroud)

GCC 12 无法编译此错误:

<source>:9:39: error: 'names' defined 'static' in 'constexpr' context
    9 |     static constexpr std::string_view names[] {
      |                                       ^~~~~
Run Code Online (Sandbox Code Playgroud)

其他编译器允许它。规则是什么?什么时候允许?

  • 我们可以static一般使用,或者
  • 只是static const,或者
  • 只是 …

c++ constants constexpr c++23

8
推荐指数
1
解决办法
205
查看次数

标签 统计

c++ ×1

c++23 ×1

constants ×1

constexpr ×1