我正在编写一个模板,可以将 c 样式多维数组转换为 std 数组并声明它。
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;
};
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 模板的可变参数。
如果你能帮助我,我将不胜感激。
最佳答案
而不是尝试使用 std::index_sequence
构建一组数组范围并将它们应用于模板参数包,为什么不定义您的特化 myArray_impl
从 typename T
递归地推导出每个范围?
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>>
关于c++ - 如何解压缩多维 c 样式数组类型并声明 std::array 实例?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65572873/