1

We can initialize, say, std::array<char, 3> with = { ' ', ' ', ' ' } but what if the size is given by a template parameter N ? Can't we do something like std::string::string(size_type count, CharT ch) which fills the instance with the given ch ?

Should I perhaps look at std::integer_sequence ?

nodakai
  • 7,773
  • 3
  • 30
  • 60
  • 3
    You can always [fill](http://en.cppreference.com/w/cpp/algorithm/fill_n) the array after definition. – Some programmer dude Dec 21 '16 at 08:41
  • @Someprogrammerdude You are talking about only non-`const` arrays. With `const`, it would become as ugly as `const std::array arr([&arr, ch] { std::remove_const_t tmp; std::fill_n(tmp.begin(), tmp.size(), ch); return tmp; }());` Well, it's doable, but... – nodakai Dec 21 '16 at 12:11

1 Answers1

3

You may use index sequence for that:

template <typename T, std::size_t...Is>
std::array<T, sizeof...(Is)> make_array(const T& value, std::index_sequence<Is...>)
{
    return {{(Is, value)...}};
}

template <std::size_t N, typename T>
std::array<T, N> make_array(const T& value)
{
    return make_array(value, std::make_index_sequence<N>());
}

Demo

Jarod42
  • 203,559
  • 14
  • 181
  • 302
  • Interesting trick to map `Is` to a sequence of `value`s, but if we need to introduce a helper function, it doesn't offer much benefits over `fill_n()` proposed in http://stackoverflow.com/questions/17923683/why-does-stdarray-not-have-an-constructor-that-takes-a-value-for-the-array-to – nodakai Dec 21 '16 at 11:45
  • @nodakai: It does the initialization once, but indeed, the two solutions are mostly equivalent. – Jarod42 Dec 21 '16 at 12:30