O'Reilly logo

Imperfect C++ Practical Solutions for Real-Life Programming by Matthew Wilson

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required