Nifty C++ Tip

I have been using this little function in the game I am writing:

template <typename Target, typename Source>
inline Target checked_cast (Source* source)
{
    // In debug, make sure that the cast is valid, using RTTI.
    assert(dynamic_cast<Target>(source));
    return static_cast<Target>(source);
}

In release, it compiles away to a static_cast, whereas in debug it will assert if the cast is invalid.

Leave a Reply