Cannot construct constexpr array from braced-init-list

Question

I've implemented a constexpr array like this:

template <typename T>
class const_array {
  const T* p;
  unsigned n;
public:
  template <unsigned N>
  constexpr const_array(const T(&a)[N]): p(a), n(N) { }

  constexpr unsigned size() const { return n; }
};

int main(int argc, char* argv[]) {

  // works
  static_assert(const_array<double>{{1.,2.,3.}}.size() == 3);

  // works
  constexpr const_array<double> a1((const double[]){1.,2.,3.});
  static_assert(a1.size() == 3);

  // doesn't compile
  constexpr const_array<double> a2{{1.,2.,3.}};
  static_assert(a2.size() == 3);
}

Can someone explain to me why the third assert doesn't compile when the first two do? I'm using gcc 6.2.0. I'm getting

: In function 'int main(int, char**)':
: error: 'const_array<double>{((const double*)(&<anonymous>)), 3u}' is not a constant expression
   constexpr const_array<double> a2{{1.,2.,3.}};
                                         ^
test/const_array.cc:31:3: error: non-constant condition for static assertion
   static_assert(a2.size() == 3);
   ^~~~~~~~~~~~~

Show source
| arrays   | c++   | constructor   | constexpr   | c++14   2017-01-02 01:01 0 Answers

Answers ( 0 )

◀ Go back