0

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

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

    protected:
        int _x;
};

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

4

2 回答 2

5

这很好,虽然有点没用:

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

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

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

constexpr int n = MyClass().test();  // 5
于 2012-09-26T15:53:37.110 回答
1

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

#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!
}
于 2012-09-26T15:56:01.680 回答