gpt4 book ai didi

c++ - 模板类型定义的数组初始化

转载 作者:行者123 更新时间:2023-11-30 02:51:27 24 4
gpt4 key购买 nike

我有一个数组,我想将其初始化为基于模板参数的 constexpr(我认为这将需要 c++14,因为我设想答案需要初始化列表作为 constexpr)。

假设我有一个模板

template<T t>

在哪里

 T = int[1][2][3]

现在,我可以使用 type_traits std::extent 递归地提取数组大小

我最终想做的是生成一个 constexpr 成员,其维度为 T 作为 myarray 的元素

std::array<int,3> myarray = {1,2,3};

我已经看到使用可变参数模板初始化数组的好方法引用:How to construct std::array object with initializer list?

问题是,如何在给定 T 的情况下生成具有 T 维度的初始化列表或可变参数模板?1

最佳答案

以下有点复杂,但它应该可以工作(使用 C++11):

#include <array>
#include <type_traits>

template<std::size_t...> struct seq {};

template<typename,typename> struct cat;
template<std::size_t... Is, std::size_t... Js>
struct cat<seq<Is...>,seq<Js...>>
{
using type = seq<Is...,Js...>;
};

template<typename> struct extract_seq { using type = seq<>; };
template<typename T,std::size_t N>
struct extract_seq<T[N]>
{
using type = typename cat< seq<N>, typename extract_seq<T>::type >::type;
};

template<typename T> struct extract_type { using type = T; };
template<typename T,std::size_t N>
struct extract_type<T[N]>
: extract_type<T>
{};

template<typename,typename> struct to_array_helper;
template<typename T, std::size_t... Is>
struct to_array_helper<T,seq<Is...>>
{
constexpr static const std::array<T,sizeof...(Is)> value {{ Is... }};
};

template<typename T, std::size_t... Is>
constexpr const std::array<T,sizeof...(Is)>
to_array_helper<T,seq<Is...>>::value;

template<typename T>
struct to_array
: to_array_helper<typename extract_type<T>::type,
typename extract_seq<T>::type>
{};

int main()
{
auto arr = to_array< int[1][2][3] >::value;
}

Live example

关于c++ - 模板类型定义的数组初始化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19695885/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com