可变参数模板:创建编译时数组

时间:2018-06-02 15:58:57

标签: c++ variadic-templates variadic-functions

我有一个函数,我想用它来在编译时创建一个数组。

template<typename... uint32_t> 
static constexpr auto AddressArray(uint32_t... ns) { 
    return std::array<uint32_t, sizeof ...(uint32_t)>{ ns... }; 
}

当我使用此代码时,出现编译错误

`compiler is out of heap space.` 

我做错了什么?

1 个答案:

答案 0 :(得分:1)

不是提供一组类型,最好为数组提供一个类型并为值包装:

template<typename T, T ...vals> 
static constexpr auto AddressArray() { 
    return std::array<T, sizeof...(vals)>{ vals... }; 
}

使用示例:

auto array = AddressArray<int, 1, 2, 4, 5>();