KSSUtil  v14.2.0
C++ general utility library
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 
60  template <typename C, typename T>
61  std::enable_if_t<!std::is_same<C, T>::value, bool>
62  inline isInstanceOf(const T& t) noexcept {
63  return dynamic_cast<const C*>(&t) != nullptr;
64  }
65 
66  template <typename C>
67  constexpr bool isInstanceOf(const C& t) noexcept {
68  return true;
69  }
70 
71  template <typename C, typename T>
72  bool isInstanceOfPtr(const T* t) {
73  if (t == nullptr) {
74  return false;
75  }
76  return isInstanceOf<C>(*t);
77  }
78 
94  template <class T, class Base>
95  T* as(Base* obj) noexcept {
96  if (!obj) { return nullptr; }
97  return dynamic_cast<T*>(obj);
98  }
99 
100  template <class T, class Base>
101  T* as(Base& obj) noexcept {
102  return as<T, Base>(&obj);
103  }
104 
105  template <class T, class Base>
106  const T* as(const Base* obj) noexcept {
107  if (!obj) { return nullptr; }
108  return dynamic_cast<const T*>(obj);
109  }
110 
111  template <class T, class Base>
112  const T* as(const Base& obj) noexcept {
113  return as<T, Base>(&obj);
114  }
115 
116 }}}
117 
118 #endif
kss::util::rtti::isInstanceOfPtr
bool isInstanceOfPtr(const T *t)
Definition: rtti.hpp:72
kss::util::rtti::name
std::string name(const T &t=T())
Definition: rtti.hpp:47
kss::util::rtti::as
T * as(Base *obj) noexcept
Definition: rtti.hpp:95
kss::util::rtti::isInstanceOf
std::enable_if_t<!std::is_same< C, T >::value, bool > isInstanceOf(const T &t) noexcept
Definition: rtti.hpp:62
kss::util::rtti::demangle
std::string demangle(const std::string &typeName)
kss
All Klassen Software Solutions libraries begin with this namespace.
Definition: add_rel_ops.hpp:19