0

In numpy, one can access the array as following

import numpy as np
a = np.arange(3*2).reshape(3, 2)
b = a[0, 1]

In c++, is it possible to overload the operator [] to implement the similar function as a[0, 1]? Of course, the number of input arguments can vary.

feedMe
  • 3,431
  • 2
  • 36
  • 61
Huayi Wei
  • 829
  • 1
  • 7
  • 16

1 Answers1

1

It is not. See the array subscript operator

To provide multidimensional array access semantics, e.g. to implement a 3D array access a[i][j][k] = x;, operator[] has to return a reference to a 2D plane, which has to have its own operator[] which returns a reference to a 1D row, which has to have operator[] which returns a reference to the element. To avoid this complexity, some libraries opt for overloading operator() instead, so that 3D access expressions have the Fortran-like syntax a(i, j, k) = x;

However a related proposal has been made to eventually enable this.

Mike Lui
  • 1,301
  • 10
  • 23
  • 1
    *To avoid this complexity* means that it's **possible** but complicated. But that answer is for accessing the element as `a[i][j][k]`, **not** as `a[i, j, k]` as the OP wants. The comma operator can be overloaded easily to [access the element as `a[i, j, k]` easily](https://stackoverflow.com/a/18136340/995714) – phuclv Feb 21 '19 at 14:05
  • @phuclv this might be viable if you overloaded it on a strong type with an explicit constructor. I can imagine the confusion otherwise, when passing multiple numbers to an unrelated function. – Mike Lui Feb 21 '19 at 15:35