1

我有一个数组,我想根据模板参数将其初始化为 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};

我已经看到了使用可变参数模板 ref 初始化数组的好方法:如何使用初始化列表构造 std::array 对象?

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

4

2 回答 2

2

以下内容有点复杂,但它应该可以工作(使用 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;
}

活生生的例子

于 2013-10-31T00:10:29.770 回答
1

我认为您不需要任何特殊的未来 C++。这在 C++11 中运行良好:

#include <array>
#include <iostream>
#include <type_traits>

#include <prettyprint.hpp>

template <typename T>
struct Foo
{
    std::array<std::size_t, std::rank<T>::value> a;

    Foo() : Foo(X<std::rank<T>::value>(), Y<>(), Z<T>()) { }

private:
    template <unsigned int K>  struct X { };
    template <unsigned int ...I> struct Y { };
    template <typename> struct Z { };

    template <typename U, unsigned int K, unsigned int ...I>
    Foo(X<K>, Y<I...>, Z<U>)
    : Foo(X<K - 1>(),
          Y<I..., std::extent<U>::value>(),
          Z<typename std::remove_extent<U>::type>())
    { }

    template <typename U, unsigned int ...I>
    Foo(X<0>, Y<I...>, Z<U>) 
    : a { I... }
    { }
};

int main()
{
    Foo<char[4][9][1]> x;
    std::cout << x.a << std::endl;
}

输出:

[4, 9, 1]
于 2013-10-30T23:51:39.650 回答