Elegantly define multi-dimensional array in modern C++

后端 未结 1 1290
遇见更好的自我
遇见更好的自我 2020-12-24 14:12

Defining multi-dimensional array using the T[][][] syntax is easy. However, this creates a raw array type which doesn\'t fit nicely into modern C++. That\'s why

相关标签:
1条回答
  • 2020-12-24 14:44

    Refer to Multi-dimensional arrays in C++11

    template <class T, std::size_t I, std::size_t... J>
    struct MultiDimArray 
    {
      using Nested = typename MultiDimArray<T, J...>::type;
      // typedef typename MultiDimArray<T, J...>::type Nested;
      using type = std::array<Nested, I>;
      // typedef std::array<Nested, I> type;
    };
    
    template <class T, std::size_t I>
    struct MultiDimArray<T, I> 
    {
      using type = std::array<T, I>;
      // typedef std::array<T, I> type;
    };
    
    MultiDimArray<float, 3, 4, 5, 6, 7>::type floats;
    

    MultiDimArray is a pair of meta-functions to compute nested type for multi-dimensional std::array. The most general MultiDimArray is a variadic template of unsigned integers to pass an arbitrary number of dimensions. The terminating MultiDimArray specialization defines the simplest case of single dimensional std::array.

    0 讨论(0)
提交回复
热议问题