Arbitrary dimensional array using Variadic templates

后端 未结 2 1270
时光取名叫无心
时光取名叫无心 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:25

    Try this:

    #include 
    
    template 
    class Array
    {
    
    public:
    
        Array() {}
    
        ~Array() {}
    
        Array& operator[](int index)
        {
            return data[index];
        }
    
    private:
    
        Array data[N1];
    };
    
    template
    class Array
    {
    
    public:
    
        Array() {}
    
        ~Array() {}
    
        T& operator[](int index)
        {
            return data[index];
        }
    
    private:
    
        T data[N];
    };
    
    int main()
    {
        Array < int, 2, 3, 4> a, b;
        Array < char, 3, 4> d;
        Array < short, 2> e;
    
        a[0][1][2] = 15;
        d[1][2]    = 'a';
    
        std::cout << "a[0][1][2] = " << a[0][1][2] << std::endl;
        std::cout << "d[1][2]    = " << d[1][2]    << std::endl;
    
        return 0;
    }
    

    You might also want to throw in range checking and perhaps some iterators to be fancy :)

提交回复
热议问题