Turn a sequence of indices into copies of an element
suggest changeExpanding the parameter pack of indices in a comma expression with a value creates a copy of the value for each of the indices. std::index_sequence and std::make_index_sequence are C++14. Sadly, gcc and clang think the index has no effect and warn about it (gcc can be silenced by casting the index to void):
#include <algorithm>
#include <array>
#include <iostream>
#include <iterator>
#include <string>
#include <utility>
template <typename T, std::size_t... I>
std::array<T, sizeof...(I)> make_array(T const& value, std::index_sequence<I...>) {
return std::array<T, sizeof...(I)>{ (I, value)... };
}
template <int N, typename T>
std::array<T, N> make_array(T const& value) {
return make_array(value, std::make_index_sequence<N>());
}
int main() {
auto array = make_array<20>(std::string("value"));
std::copy(array.begin(), array.end(),
std::ostream_iterator<std::string>(std::cout, " "));
std::cout << "\n";
}
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents