Lewis Liman
Lewis Liman

Reputation: 553

How to programmatically generate std::index_sequence of same values without having to do recursive template instantiation for every element

#include <utility>

template<std::size_t Value, std::size_t Count, typename T = std::index_sequence<>>
struct index_sequence_of_same_value;

template<std::size_t Value, std::size_t Count, std::size_t... Rest>
struct index_sequence_of_same_value<Value, Count, std::index_sequence<Rest...>>
{
    using type = typename index_sequence_of_same_value<Value, Count - 1, std::index_sequence<Value, Rest...>>::type;
};

template<std::size_t Value, std::size_t... Rest>
struct index_sequence_of_same_value<Value, 0, std::index_sequence<Rest...>>
{
    using type = std::index_sequence<Rest...>;
};

template<std::size_t Value, std::size_t Count, typename T = std::index_sequence<>>
using make_index_sequence_of_same_value= typename index_sequence_of_same_value<Value, Count, T>::type;


int main()
{
    make_index_sequence_of_same_value<4, 6> t; // std::integer_sequence<std::size_t, 4, 4, 4, 4, 4, 4>
}

This seems straight forward using recursive template instantiation. But this implementation is very slow and also limiting since it has to recursively instantiate template instances for each element.

Is there another way to do something similar to this without instantiating templates for number of elements?

Upvotes: 1

Views: 385

Answers (1)

Igor Tandetnik
Igor Tandetnik

Reputation: 52471

Something like this perhaps:

template <std::size_t Value, std::size_t... Is>
std::index_sequence<(Is, Value)...> make_sequence_helper(
    std::index_sequence<Is...>);  // no definition

template<std::size_t Value, std::size_t Count>
using make_index_sequence_of_same_value =
    decltype(make_sequence_helper<Value>(std::make_index_sequence<Count>()));

Demo

Upvotes: 2

Related Questions