KSS Utility
C++ general utilities
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends
rtti.hpp
Go to the documentation of this file.
1 //
2 // rtti.hpp
3 // kssutil
4 //
5 // Created by Steven W. Klassen on 2014-01-22.
6 // Copyright (c) 2014 Klassen Software Solutions. All rights reserved.
7 // Licensing follows the MIT License.
8 //
9 
15 #if !defined(kssutil_rtti_h)
16 #define kssutil_rtti_h
17 
23 #include <string>
24 #include <type_traits>
25 #include <typeinfo>
26 
27 namespace kss { namespace util { namespace rtti {
28 
37  std::string demangle(const std::string& typeName);
38 
46  template <typename T>
47  inline std::string name(const T& t = T()) {
48  return demangle(typeid(t).name());
49  }
50 
61  template <typename C, typename T>
62  bool isInstanceOf(const T& t) noexcept {
63  if (std::is_base_of<C, T>::value) {
64  return true;
65  }
66  if (dynamic_cast<const C*>(&t) != nullptr) {
67  return true;
68  }
69  return false;
70  }
71 
72  template <typename C, typename T>
73  bool isInstanceOfPtr(const T* t) {
74  if (t == nullptr) {
75  return false;
76  }
77  return isInstanceOf<C>(*t);
78  }
79 
95  template <class T, class Base>
96  T* as(Base* obj) noexcept {
97  if (!obj) { return nullptr; }
98  return dynamic_cast<T*>(obj);
99  }
100 
101  template <class T, class Base>
102  T* as(Base& obj) noexcept {
103  return as<T, Base>(&obj);
104  }
105 
106  template <class T, class Base>
107  const T* as(const Base* obj) noexcept {
108  if (!obj) { return nullptr; }
109  return dynamic_cast<const T*>(obj);
110  }
111 
112  template <class T, class Base>
113  const T* as(const Base& obj) noexcept {
114  return as<T, Base>(&obj);
115  }
116 
117 }}}
118 
119 #endif
std::string demangle(const std::string &typeName)
bool isInstanceOf(const T &t) noexcept
Definition: rtti.hpp:62
bool isInstanceOfPtr(const T *t)
Definition: rtti.hpp:73
T * as(Base *obj) noexcept
Definition: rtti.hpp:96
std::string name(const T &t=T())
Definition: rtti.hpp:47