Chapter 27. Subscript Operators

Pointer Conversion versus Subscript Operators

I mentioned earlier (see section 14.2.2) that one must choose between providing implicit conversion to a pointer (to the managed sequence) or subscript operators. In this section, we'll see why. Consider the code in Listing 27.1.

Example 27.1. 

typedef size_t  subscript_arg_t;
typedef int     indexer_t;
struct DoubleContainer
  typedef size_t  size_type;
               operator double const *() const;
               operator double *();
  double const &operator [](size_type index) const;
  double       &operator [](size_type index);
  size_type    size() const;
. . .
DoubleContainer dc;
indexer_t       index = 1;
dc[index];  // S#1
dc[0];      // S#2

Most types that provide subscripting can only support non-negative indexes, so ...

Get Imperfect C++ Practical Solutions for Real-Life Programming now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.