NOTE The C++ Answer Book (Hansen) also shows an instance of this technique: a SubString class which is a view onto a String class.
Another example of this surrogate is making a bit-vector class that looks like an array of Booleans; specifically, you can use this surrogate to implement the subscript operator. It's fairly easy to define an operator that returns a Boolean:
This solution illustrates a powerful technique that the Taligent C++ Compiler does well; but be aware that some compilers generate abysmal code for this.
But this can't appear on the left side of an assignment because you can't return a Boolean operator [](int foo);
Boolean&
--there is no Boolean to return a reference to (remember, it is a bit vector). Instead, define a TBit class that the subscript operator returns:
TBit has assignment defined for Boolean arguments--TBit operator [](int foo);
TBit& operator=
(Boolean)--and also has a coercion operator for changing it into a Boolean--operator Boolean(). It's implemented as a friend class of TBitVector or uses public SetBit and TestBit functions. On assignment of a Boolean, it does a SetBit on the corresponding bit, and it does a TestBit on coercion to Boolean.
[Contents]
[Previous]
[Next]
Click the icon to mail questions or corrections about this material to Taligent personnel.