在 constexpr 中使用的非常量:标准怎么说

Non-const used in a constexpr : what does the standard say?

本文关键字:常量 标准 怎么说 非常 constexpr      更新时间:2023-10-16

C++11 iso 标准对这样的表达式有什么看法:

class MyClass
{
    public:
        constexpr int test()
        {
            return _x;
        }
    protected:
        int _x;
};

_x constexpr中使用非常量:它会产生错误,还是简单地忽略constexpr(就像我们传递非常量参数时一样)?

这很好,虽然有些没用:

constexpr int n = MyClass().test();

由于MyClass是一个聚合,因此像这样对其进行值初始化将对所有成员进行值初始化,因此这只是零。但是通过一些润色,这可以变得真正有用:

class MyClass
{
public:
    constexpr MyClass() : _x(5) { }
    constexpr int test() { return _x; }
// ...
};
constexpr int n = MyClass().test();  // 5

如果表达式未解析为常量表达式,则不能将其用作常量表达式。但它仍然可以使用:

#include <array>
constexpr int add(int a, int b)
{
  return a+b;
}
int main()
{
  std::array<int, add(5,6)> a1; // OK
  int i=1, 
  int j=10;
  int k = add(i,j); // OK
  std::array<int, add(i,j)> a2; // Error!
}