如何解压多维 C 样式数组类型并声明 std::array 实例?

How can I unpack multidimensional c-style array type and declare std::array instance?

我正在编写一个模板,可以将 c 样式的多维数组转换为标准数组并进行声明。

  1. 获取c风格数组矩阵
template <typename, typename IS = std::index_sequence<>>
struct unpacked_array_type_impl
{
    using type = IS;
};

template <typename T, std::size_t ... I>
struct unpacked_array_type_impl<T*, std::index_sequence<I...>>
    : public unpacked_array_type_impl<T, std::index_sequence<0u, I...>>
{ };

template <typename T, std::size_t N, std::size_t ... I>
struct unpacked_array_type_impl<T[N], std::index_sequence<I...>>
    : public unpacked_array_type_impl<T, std::index_sequence<I..., N>>
{ };

template<typename T>
struct unpacked_array_type
{
    using type = typename unpacked_array_type_impl<T>::type;
};
  1. 标准数组声明
template<typename T, size_t size, size_t... more>
struct myArray_impl
{
    using type = std::array<typename myArray_impl<T, more...>::type, size>;
};

template<typename T, size_t size>
struct myArray_impl<T, size>
{
    using type = std::array<T, size>;
};

template<typename T, size_t size, size_t... more>
using myArray = typename myArray_impl<T, size, more...>::type;

下面是我要实现的代码。

using example_type = int[4][10];
using real_type = std::remove_all_extents<example_type>::type
myArray<real_type, unpacked_array_type<example_type>::type> this_would_be_std_arr;

但是我遇到了 C2993 错误。

问题是 std::integer_sequence 无法扩展到 myArray 模板的变量参数。

如果你能帮助我,我将不胜感激。

第一个模板returnstd::index_sequence,而第二个模板采用数字列表。

您可以对两者使用 std::index_sequence

template<typename T, typename Seq>
struct myArray_impl;


template<typename T, size_t size, size_t... more>
struct myArray_impl<T, std::index_sequence<size, more...>>
{
    using type = std::array<typename myArray_impl<T, std::index_sequence<more...>>::type, size>;
};

template<typename T, size_t size>
struct myArray_impl<T, std::index_sequence<size>>
{
    using type = std::array<T, size>;
};

template<typename T, typename Seq>
using myArray = typename myArray_impl<T, Seq>::type;

Demo.

与其尝试使用 std::index_sequence 构建数组范围堆栈并将它们应用于模板参数包,不如定义 myArray_impl 的特化以递归地从 [= 中推导出每个范围14=]?

template <typename T>
struct myArray_impl
{
    using type = typename std::remove_cv<T>::type;
};

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

template <typename T>
using myArray = typename myArray_impl<T>::type;

然后你得到以下示例类型别名:

myArray<const int[4]> // std::array<int, 4>>
myArray<float[4][10]> // std::array<std::array<float, 10>, 4>>