c++ - How to tell if a type is a subclass using type_info? -
i use c++ rtti. have type_info
of class. how can tell whether class subclass of first one, if have type_info
?
#include <typeinfo> class foo { public: virtual ~foo() {} }; class boo: public foo { public: virtual ~boo() {} }; class bar { public: virtual ~bar() {} }; template<class t> bool instanceof(const type_info& info) { // answer comes here!! } int main(int argc, const char* argv[]) { const type_info& fooinfo = typeid(foo); const type_info& barinfo = typeid(bar); bool booisfoo = instanceof<boo>(fooinfo); // should true bool booisbar = instanceof<boo>(barinfo); // should false return 0; }
if have 2 typeinfo , b. there no general way determine if subclass of b.
you may:
- store information (static structure filled @ runtime?)
- make educated guesses using type name (i.e. parsing type info string , name types accordingly).
previous answers. require instantiate type somehow:
type_info
not right tool this, should dynamic_cast
if absolutely want check @ runtime:
template<class base, typename derived> bool instanceof(const derived& object) { return !dynamic_cast<base*>(object); }
you can check @ compile time using std::is_base_of
steephen mentioned (c++11 needed).
template <typename base, typename derived> static constexpr bool instanceof() { return std::is_base_of<base, derived>() }
another solution:
template <typename base, typename derived> bool instanceof(const derived& object) { try { throw object; } catch (const base&) { return true; } catch (...) { return false; } }
Comments
Post a Comment