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

标签 c++ templates std metaprogramming

我正在编写一个模板,可以将 c 样式多维数组转换为 std 数组并声明它。

  • 获取 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;
    };
    
  • 标准数组声明
  • 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_impltypename 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/

    相关文章:

    c++ - 审核 bash RPG 的 bash 命令

    c++ - 将 QLineEdit 变量的值分配给 QStringList 变量

    c++ - 在模板化构造函数中调用构造函数时的有趣行为

    templates - dlang 模板和模板化类、结构和函数之间的区别

    c++ - 识别导致 "non-POD type ' 类段“”的错误

    C++ 通过指针访问私有(private)函数

    c++ - 在这个 boost asio 示例中,为什么 io_service 在调用 .async_accept 之后启动

    html - 便宜/免费的 "Look and Feel"Web 应用程序框架

    c++ - 在什么情况下我必须使用 std::function?

    c++ - 如何使用 std::scoped_allocator_adapter?