2

How does subscripting multiple times work for std::array even though all operator[]returns is a reference, without using any proxy-objects (as shown here)?

Example:

#include <iostream>
#include <array>

using namespace std;

int main()
{

    array<array<int, 3>, 4> structure;
    structure[2][2] = 2;
    cout << structure[2][2] << endl;

    return 0;
}

How/why does this work?

Community
  • 1
  • 1
TeaOverflow
  • 2,468
  • 3
  • 28
  • 40
  • When performing operations on references, you perform them on objects they refer to. – W.B. Sep 10 '14 at 15:11
  • 4
    The example you link to shows how to use a proxy object so that you can subscript an object multiple times when you have a single object that _models_ a multidimensional array. With `array, M>` you literally have an array of arrays, so subscripting the outer object returns a reference to an array, which you can then subscript. No proxy needed, because this case is much simpler! – Jonathan Wakely Sep 10 '14 at 15:11
  • When you have a pointer `int*p`, you can compute `p+6+2`. Same thing. – Marc Glisse Sep 10 '14 at 15:14

2 Answers2

7

You simply call structure.operator[](2).operator[](2), where the first operator[] returns a reference to the third array in structure to which the second operator[] is applied.

Note that a reference to an object can be used exactly like the object itself.

Baum mit Augen
  • 49,044
  • 25
  • 144
  • 182
6

As you say, structure[2] gives a reference to an element of the outer array. Being a reference, it can be treated exactly as if it were an object of the same type.

That element is itself an array (array<int,3>), to which a further [] can be applied. That gives a reference to an element of the inner array, of type int.

Mike Seymour
  • 249,747
  • 28
  • 448
  • 644