0

Is there in c++ a possibility to create a variable length initializer_list?

As Example:

std::list<string>  mylist { somemagic (listSize, "default") };

Or:

QList<MyClass>     anotherList { somemagic (listSize, {MyClassInitializerHere} ) };
Brodie
  • 429
  • 1
  • 5
  • 16
eddy
  • 488
  • 5
  • 18

2 Answers2

2

No, initializer_list can only be created from a braced-init-list {el1, el2, ...}, whose length has to be a compile-time constant.

If the length is a compile-time constant, then you can construct a braced-init-list from a variadic expansion of a std::index_sequence; however, it is likely to be more straightforward to use the fill constructor of std::list:

std::list<string>  mylist(listSize, "default");

You can do the same for QList by exploiting the fromStdList constructor function:

QList<string>  mylist = QList<string>::fromStdList(
    std::list<string>(listSize, "default"));
ecatmur
  • 152,476
  • 27
  • 293
  • 366
1

You may use the following: (https://ideone.com/eQstbh)

#include <initializer_list>

#if 1 // Not in C++11 // make_index_sequence
#include <cstdint>

template <std::size_t...> struct index_sequence {};

template <std::size_t N, std::size_t... Is>
struct make_index_sequence : make_index_sequence<N - 1, N - 1, Is...> {};

template <std::size_t... Is>
struct make_index_sequence<0u, Is...> : index_sequence<Is...> {};

#endif // make_index_sequence

namespace detail
{
    template <std::size_t... Is, typename T>
    std::initializer_list<T> make_initializer_list(const T& t, index_sequence<Is...>)
    {
        return { (static_cast<void>(Is), t)... };
    }
}


template <std::size_t N, typename T>
std::initializer_list<T> make_initializer_list(const T& t)
{
    return detail::make_initializer_list(t, make_index_sequence<N>());
}
Jarod42
  • 203,559
  • 14
  • 181
  • 302