C++11 initialize array with uniform value in constexpr function

Posted by marack on Stack Overflow See other posts from Stack Overflow or by marack
Published on 2014-05-28T01:13:02Z Indexed on 2014/05/28 3:25 UTC
Read the original article Hit count: 144

Filed under:
|
|

I have a class template which builds a simple array based on the template parameters as one of its members. I need to be able to initialize every element in the array to a single value in one of the constructors. Unfortunately this constructor must be constexpr.

The relevant part boils down to:

template <typename T, size_t N>
class foo
{
  T data[N];

  constexpr foo(T val)
  {
    // initialize data with N copies of val
  }
};

Using std::fill or a loop is incompatible with the constexpr requirement. Initializing with : data{val} only sets the first element of the array and zero-initializes the remainder.

How can this be achieved?

I feel like there should be a solution with variadic templates and tuples etc...

© Stack Overflow or respective owner

Related posts about c++

Related posts about c++11