Previous section   Next section

Imperfect C++ Practical Solutions for Real-Life Programming
By Matthew Wilson
Table of Contents
Chapter 33.  Multidimensional Arrays


33.1. Facilitating Subscript Syntax

We've already seen (see Chapter 14 and section 27.1) that we can facilitate subscripting for one-dimensional arrays by simply providing an implicit conversion to a pointer to the element type.



struct IntArray1D


{


  operator int *()


  {


    return m_elements;


  }


  int m_elements[3];


};





IntArray1D  ia;


ia[2] = ia[1] + 1;



We do not have the option to do this with arrays of any higher dimensionality, because the array decay that facilitates this shortcut is not available (see section 14.2). The following class has an implicit conversion to a pointer to a pointer to an int, which is quite a different thing to an implicit conversion to a two-dimensional array; if it were not, how would the compiler know how to calculate the most significant offset in the following case?



struct IntArray2D


{


  operator int **()


  {


    return m_elements; // Illegal


  }


  int m_elements[3][3];


};


IntArray2D  ia;


ia[2][2] = ia[2][1] + 1; // Compiler cannot deduce dimensions!



The only way for us to support natural syntax for multiple dimensions is to overload the subscript operator for the outermost dimension, and to have that return something that can be subscripted. In the case of a two-dimensional array, we could have the subscript operator return either a type that provides the subscript operator or one that provides an implicit conversion to a pointer. For any higher dimension, the type returned must be one that returns a type that overloads the subscript operator.


      Previous section   Next section