// $Id: checked_cast.hh 5609 2006-09-07 18:28:41Z m9710797 $ #ifndef CHECKED_CAST_HH #define CHECKED_CAST_HH /** * Based on checked_cast implementation from the book: * C++ Coding Standard * item 93: Avoid using static_cast on pointers */ #include /* IMHO this implementation is simpler, but gcc-3.4 and below don't * correctly handle overloading with it (ambiguous overload). * * template struct remove_reference * { * typedef T type; * }; * template struct remove_reference * { * typedef T type; * }; * * template * static TO checked_cast(FROM* from) * { * assert(dynamic_cast(from) == static_cast(from)); * return static_cast(from); * } * template * static TO checked_cast(FROM& from) * { * typedef typename remove_reference::type* TO_PTR; * assert(dynamic_cast(&from) == static_cast(&from)); * return static_cast(from); * } * * Implementation below can only handle const references, need to find a way * around that. */ template struct checked_cast_impl {}; template struct checked_cast_impl { inline TO* operator()(FROM from) { assert(dynamic_cast(from) == static_cast(from)); return static_cast(from); } }; template struct checked_cast_impl { inline TO& operator()(const FROM& from) { assert(dynamic_cast(&from) == static_cast(&from)); return static_cast(from); } }; template static inline TO checked_cast(const FROM& from) { checked_cast_impl caster; return caster(from); } #endif