简体   繁体   中英

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM