2443. std::array member functions should be constexpr

Section: 26.3.7 [array] Status: Resolved Submitter: Peter Sommerlad Opened: 2014-10-06 Last modified: 2017-03-13

Priority: Not Prioritized

View all other issues in [array].

View all issues with Resolved status.

Discussion:

When experimenting with C++14 relaxed constexpr functions I made the observation that I couldn't use std::array to create a table of data at compile time directly using loops in a function. However, a simple substitute I could use instead:

template <typename T, size_t n>
struct ar {
  T a[n];
  constexpr ar() : a{{}}{}
  constexpr auto data() const { return &a[0];}
  constexpr T const & operator[](size_t i) const { return a[i]; }
  constexpr T & operator[](size_t i) { return a[i]; }
};

template <size_t n>
using arr = ar<size_t, n>; // std::array<size_t, n>;

template <size_t n>
constexpr auto make_tab(){
  arr<n> result;
  for(size_t i=0; i < n; ++i)
    result[i] = (i+1)*(i+1); // cannot define operator[] for mutable array...
  return result;
}

template <size_t n>
constexpr auto squares=make_tab< n>();

int main() {
  int dummy[squares<5>[3]];
}

Therefore, I suggest that all member functions of std::array should be made constexpr to make the type usable in constexpr functions.

Wording should be straight forward, may be with the exception of fill, which would require fill_n to be constexpr as well.

[2014-11 Urbana]

Move to LEWG

The extent to which constexpr becomes a part of the Library design is a policy matter best handled initially by LEWG.

[08-2016, Post-Chicago]

Move to Tentatively Resolved

Proposed resolution:

This functionality is provided by P0031R0