Previous section   Next section

Imperfect C++ Practical Solutions for Real-Life Programming
By Matthew Wilson
Table of Contents
Chapter 19.  Casts


19.10. Casts: Coda

We've seen how casts can be implemented either as functions or as classes. The former represent the more straightforward approach, but are underpowered for many tasks. Using classes allows us to make specializations to factor out common code from several casts into a common parent class and to more easily constrain the potential uses of the casts. When implementing casts as classes, measures should be taken to minimize the potential for abuse of the class (cast) instances that must only be used as temporaries. These measures include restricting the set of class operators, the types returned by these methods, and clearly documenting the semantics of the classes.

We've also focused on cast failure. The C++ casts have fixed and well-defined behavior for failure to cast. Upon failure, const_cast, static_cast, and reinterpret_cast all fail to compile, while at run time dynamic_cast returns a null pointer for failed pointer casts or throws an instance of std::bad_cast for failed reference casts. When implementing a castlike operator, the failure response must be carefully considered. Whenever possible, compile-time failure is preferred to run time failure. explicit_cast and literal_cast fail at compile time. union_cast fails primarily at compile time. The interface casts and ptr_cast necessarily fail at run time.

For run time failure, it can be unclear clear whether returning a null value or throwing an exception is the best choice. This is especially so when providing general-purpose and/or open-source libraries, where it is impossible to anticipate all the contexts in which your code will find itself and unhelpful to prescribe limitations. In such situations, it is nice to be able to use a parameterizable policy, as with interface_cast_addref.


      Previous section   Next section