You can also abandon direct uses of dynamic_cast
and wrap it in your own template machinery:
#include <sstream>
class my_bad_cast: public std::bad_cast {
public:
my_bad_cast(char const* s, char const* d): _source(s), _destination(d) {
#ifdef WITH_BETTER_WHAT
try {
std::ostringstream oss;
oss << "Could not cast '" << _source
<< "' into '" << _destination << "'";
_what = oss.str();
} catch (...) {
_what.clear();
}
#endif
}
char const* source() const { return _source; }
char const* destination() const { return _destination; }
#ifdef WITH_BETTER_WHAT
virtual char const* what() const noexcept {
return not _what.empty() ? _what.c_str() : std::bad_cast::what();
}
#endif
private:
char const* _source;
char const* _destination;
#ifdef WITH_BETTER_WHAT
std::string _what;
#endif
// you can even add a stack trace
};
template <typename D, typename S>
D my_dynamic_cast(S&& s) {
try {
return dynamic_cast<D>(std::forward<S>(s));
} catch(std::bad_cast const&) {
throw my_bad_cast(typeid(S).name(), typeid(D).name());
}
}