C++ already has a rich set of casting operatos, ranging from old-style C casts, over static_cast, dynamic_cast and the almost-never-to-be-used reinterpret_cast. Sometimes it might be convenient to have something similar like a dynamic_cast but with another behaviour if the cast fails. For example one might want to get an exception if a specific cast is not possible.
It turns out that this is pretty easy using templates with the following code
template<class T,class S> T* throwing_cast(S* s) {
T* result = dynamic_cast<T>(s);
if (!result)
throw bad_cast_exception();
return result;
}
ClassA* a = new ClassB();
ClassB* b = throwing_cast<ClassB>(a);
But we still can do better than this, because we might want to configure which exception should be thrown on a casting failure. The code above can be easily modified to:
Continue reading "New cast operators with additional features"