How to implement the [] operator for this structure?

I want to have something like this below:

template <class T>
struct Container{
 public:
  //[] operator
 private:
  T containment;
};

the shell should be an array with any sample number of dimensions, as shown below:

Container<int[20][4]> obj;
Container<int[5][2][6]> obj1;
//etc...

And I want to implement the [] operator so that the following assignments can be made:

obj[2][3]=6;
obj1[1][1][3]=3;
//etc...

But after several attempts I ended up stuck, how is this possible?

+3
source share
5 answers

Who thought a link would come into play here? me!
Thanks to Niki Yoshiuchi, the answer in the exact structure that I want is as follows:

template <class T, size_t N>
struct Container {
private:
 T containment[N];
public:
 T & operator[](size_t index) { return containment[index]; }
};

Container<int[3][3][3],2> obj;
obj[1][1][1][1]=7;
+1
source

Your subscription operator should return a proxy object that the subscription operator will implement.

obj[2][3] = 6, :

  • obj[2] → -
  • obj[2][6]int

obj1, , , [] -.

"depth" . T , , ( ).

, . , , .

+5

( , ).

template <class T, size_t m, size_t n>
struct Container{
 public:
  int& operator()(size_t i, size_t j)
  {
      return containment[i][j];
  }

 private:
  T containment[m][n];
};

Container<int, 3, 4> ints;
ints(0,3) = 5;

Boost.MultiArray .

Boost MultiArray ++ . , ++ . , , .

+3

, operator[]. - :

template <class T, size_t N>
struct Container {
T containment[N];
T &operator[](size_t index) { return containment[index]; }
};

Container<int[2][6], 5> obj;

:

Container<Container<Container<int[6]>[2]>[5]> obj;
+2

n- . , .

template< typename T >
class MultiDimContainer
{
   std::vector<size_t> dims;

   std::vector<T> data;

public:
   MultiDimContainer( const std::vector<size_t> dims )
   {
       // work out the product of dims and set data to that size
   }

   T& at( const std::vector<size_t> & dim )
   {
      // calculate where it lives in memory and return that element
   }
};

() , []. , , 2 , , () , [] . , ( ) .

, - , .

[] , _t ContainerReferencer. , , . .

[] T value_type .

, . , , 4-,

MultiDimCollection < double, 4 >

4 . [], MultiDimCollectionReference < double, 3 >

2 1 (), .

0

Source: https://habr.com/ru/post/1776269/


All Articles