Is it possible to create an std::initializer_list<int>
of 1000 elements all initialized to value 5
? As far as I know the only way of creating an std::initializer_list<int>
of 1000 elements all initialized to 5
is std::initializer_list<int> { 5, 5, 5, ....1000 times };
. I'm looking for a shorter syntax.
Asked
Active
Viewed 74 times
0

Harry
- 2,177
- 1
- 19
- 33
-
1Why should it be `std::initializer_list`? What do you want to initialize with that? Asking, because `std::vector` for example has a constructor suited for this, and `std::array` could be filled using `std::fill`. – Yksisarvinen Nov 19 '20 at 13:04
-
@Yksisarvinen I need to pass an `std::initializer_list
` as argument to a library function – Harry Nov 19 '20 at 13:06 -
With the given description my advise is to just use copy/paste and make your initializer list literally. Anything else is going to stress the compiler in needless ways. – tenfour Nov 19 '20 at 13:10
1 Answers
4
You can use variadic pack expansions with std::index_sequence
to create an initializer list with an arbitrary number of elements. Since you can't return a std::initializer_list
from a function safely (see this question), you need to wrap the function call, for example:
template<template Fn, std::size_t ...Ns>
decltype(auto) apply_init_list(Fn &&fn, std::index_sequence<Ns...>)
{
return std::forward<Fn>(fn)({ ((void)Ns, 5)... });
// ^~~~~~ ^ comma operator
// |
// cast to void to avoid unused value compiler warnings
}
And use it like
// ...
auto value = apply_init_list(&some_library_function, std::make_index_sequence<1000>{});
// ...

IlCapitano
- 1,994
- 1
- 7
- 15