Arbitrary dimensional array using Variadic templates

后端 未结 2 1259
时光取名叫无心
时光取名叫无心 2020-12-21 09:22

How can I create an Array class in C++11 which can be used like

Array < int, 2, 3, 4> a, b; 
Array < char, 3, 4> d; 
Array < short, 2> e;
         


        
2条回答
  •  情歌与酒
    2020-12-21 10:17

    The simplest way to do this is by nesting std::array:

    #include
    
    template
    struct ArrayImpl {
        using type = std::array::type, size>;
    };
    
    template
    struct ArrayImpl {
        using type = std::array;
    };
    
    template
    using Array = typename ArrayImpl::type;
    

    In this solution Array is the same as std::array, 3> - array consisting of arrays of smaller dimension.

    This also shows how you can implement operator[] for many dimensions. operator[] of your object needs to return object for which operator[] is also defined. In this case it is reference to an array of smaller dimension.

提交回复
热议问题