Surrogates that view masters

This kind of surrogate object encapsulates information about an aspect of the master object, but is not necessarily a true surrogate for the master. Instead, it is a synthetic or virtual perspective on that object, and it does not necessarily share a common base class. In the Taligent Application Environment, iterators associated with the Collection classes are such surrogates.

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:

    Boolean operator [](int foo);
But this can't appear on the left side of an assignment because you can't return a 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 operator [](int foo);
TBit has assignment defined for Boolean arguments--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.

This solution illustrates a powerful technique that the Taligent C++ Compiler does well; but be aware that some compilers generate abysmal code for this.


[Contents] [Previous] [Next]
Click the icon to mail questions or corrections about this material to Taligent personnel.
Copyright©1995 Taligent,Inc. All rights reserved.

Generated with WebMaker