c++ - 如何根据可变参数模板的大小自动填充 std::array?

标签 c++ templates c++11 variadic-templates c++14

在这个简化的代码中:

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)>{});

关于c++ - 如何根据可变参数模板的大小自动填充 std::array?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24147819/

相关文章:

c++ - 为什么下面的类不对数组 arr 进行浅拷贝?

c++ - mem_func 和 for_each 用法

c++ - 从其他文件C++的模板类调用静态方法

C++:将成员变量的引用/指针作为模板参数

Azure ARM模板“找不到名称为hostingEnvironment

c++ - 使用 `std::greater` 通过 `priority_queue` 创建最小堆的原因

c++ - std::algorithm 的便利层

c++ - 两个不同的进程在同一地址上有 2 个 std::atomic 变量?

c++ - 带取消引用和不带取消引用的函数有什么区别

c++ - 用于将数组转换为 vector 的 Memcpy