Vincent
Vincent

Reputation: 60341

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

What does the C++11 iso standard say about such an expression :

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

    protected:
        int _x;
};

_x is a non-const used in a constexpr : will it produce an error, or will the constexpr be simply ignored (as when we pass a non-const parameter) ?

Upvotes: 0

Views: 129

Answers (2)

Kerrek SB
Kerrek SB

Reputation: 476930

It's perfectly fine, though somewhat useless:

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

Since MyClass is an aggregate, value-initializing it like that will value-initialize all members, so this is just zero. But with some polish this can be made truly useful:

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

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

Upvotes: 5

juanchopanza
juanchopanza

Reputation: 227370

If the expression does not resolve to a constant expression, then it cannot be used as such. But it can still be used:

#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!
}

Upvotes: 1

Related Questions