Previous fileTop of DocumentContentsIndex pageNext file
Apache C++ Standard Library User's Guide

38.5 Using iword/pword for RTTI in Derived Streams

In the previous section, we discussed an example that used runtime-type identification (RTTI) to enable a given input or output operation to adapt its behavior based on the properties of the respective stream type.

Before RTTI was introduced into the C++ language in the form of the new style dynamic_cast<>, the problem was solved using iword(), pword(), and xalloc() as substitutes for RTTI. We describe this alternative technique only briefly because, as the previous example suggests, the use of dynamic casts is clearly preferable to this technique.

The basic idea of the traditional technique is that the stream class and all functions and classes that need the runtime type information, like the inserter and the manipulator function, agree on two things:

In the following sketch, the derived stream class reserves an index into the additional storage. The index is a static data member of the derived stream class, and identifies all objects of that stream class. The content of that particular slot in the stream's additional storage, which is accessible through pword(), is expected to be the respective stream object's this pointer.

Here are the modifications to the derived class odatstream:

//1The static const member xindex is initialized with an index unique to each specialization of odatstream.
//2The reserved slot in the arrays for additional storage is filled with the object's own address.

Here are the corresponding modifications to the manipulator:

//1The manipulator function checks whether the content of the reserved slot in the stream's storage is the stream's address. If it is, the stream is considered to be a date output stream.

Note that the technique described in this section is not safe. There is no way to ensure that date output streams and their related functions and classes are the only ones that access the reserved slot in a date output stream's additional storage. In principle, every stream object of any type can access all entries through iword() or pword(). It's up to your programming discipline to restrict access to the desired functions. It is unlikely, however, that all streams will make the same assumptions about the storage's content. Instead of agreeing on each stream object's address as the run-time-type identification, we also could have stored certain integers, pointers to certain strings, etc. Remember, it's the combination of reserved index and assumed content that represents the RTTI substitute.



Previous fileTop of DocumentContentsIndex pageNext file