Open dmcdougall opened 10 years ago
We'd ifdef
around NDEBUG
so that if we're in debug mode we do a dynamic_cast
and rely on RTTI. Whilst, if we're not in debug mode we do a static_cast
. This can't be done in a macro because we need to know the type of the converted-to thing. This is most suited to a template function that has the converted-to type as a template parameter.
Reading the documentation for dynamic_cast
, it appears that the return value (and its type) depends on the type of the conversion being done:
If the cast is successful, dynamic_cast returns a value of type new_type. If the cast fails and new_type is a pointer type, it returns a null pointer of that type. If the cast fails and new_type is a reference type, it throws an exception that matches a handler of type std::bad_cast.
This means we can't just have one queso_cast<T>
, we'd need one for pointer types (queso_cast_pointer), reference types (queso_cast_reference), and then everything else (queso_cast). Then again, maybe we could play some template metaprogramming games to determine whether or not T
is a pointer type or reference type so we don't need multiple versions of casting functions.
Lastly, it occurs to me that maybe one template parameter for the converted-to thing isn't enough. The argument to dynamic_cast
takes an arbitrary type, too, so we'd need one template parameter type for the converted-to thing, and another template parameter for the converted-from thing.
Aha! Awesome, thank you.
See here for details.