如何基于可变进模板的sizeof自动填充std::数组

How to automatically fill a std::array base on sizeof a variadic template?

本文关键字:填充 std 数组 sizeof 何基于      更新时间:2023-10-16

在这个简化的代码中:

template <int... vars>
struct Compile_Time_Array_Indexes
{
    static std::array < int, sizeof...(vars)> indexes;//automatically fill it base on sizeof...(vars)
};
template <int ... vars>
struct Compile_Time_Array :public Compile_Time_Array_Indexes<vars...>
{
};

我想根据vars...的大小自动填充indexes

示例:

Compile_Time_Array <1,3,5,2> arr1;//indexes --> [0,1,2,3]
Compile_Time_Array <8,5> arr2;   // indexes --> [0,1]

下面的定义显然适用于GCC-4.9和Clang-3.5:

template <typename Type, Type ...Indices>
auto make_index_array(std::integer_sequence<Type, Indices...>)
    -> std::array<Type, sizeof...(Indices)>
{
    return std::array<Type, sizeof...(Indices)>{Indices...};
}
template <int... vars>
std::array<int, sizeof...(vars)> 
Compile_Time_Array_Indexes<vars...>::indexes
    = make_index_array<int>(std::make_integer_sequence<int, sizeof...(vars)>{});