Gray C++ Libraries  0.0.2
A set of C++ libraries for MSVC, GNU on Windows, WinCE, Linux
PtrCast.h
Go to the documentation of this file.
1 //
5 //
6 
7 #ifndef _INC_PtrCast_H
8 #define _INC_PtrCast_H
9 #ifndef NO_PRAGMA_ONCE
10 #pragma once
11 #endif
12 
13 #include "cDebugAssert.h"
14 
15 namespace Gray
16 {
17 
18 #ifdef _CPPRTTI
19 #define DYNPTR_CAST(t,p) (dynamic_cast <t*>(p)) // typically used for safer down-casting.
20 #define IS_TYPE_OF(t,p) ((dynamic_cast<const t*>(p))!=nullptr)
21 #else
22 #define DYNPTR_CAST(t,p) (static_cast <t*>(p)) // dynamic_cast isn't available ?
23 #define IS_TYPE_OF(t,p) true
24 #endif
25 
26  template <class _TYPE_TO, class _TYPE_FROM >
27  inline bool is_valid_cast(_TYPE_FROM* p)
28  {
29  // will dynamic_cast work ? AKA IS_TYPE_OF() ? std::is_base_of()
30  // TODO typeid(p) == typeid(_TYPE_TO); as dynamic? or IS_TYPE_OF(_TYPE_TO)
31  if (p == nullptr)
32  return true;
33  _TYPE_TO* p2 = dynamic_cast<_TYPE_TO*>(p);
34  return p2 != nullptr ;
35  }
36 
37  template <class _TYPE_TO, class _TYPE_FROM >
38  inline _TYPE_TO* check_cast(_TYPE_FROM* p)
39  {
44 #ifdef _DEBUG
45  ASSERT(is_valid_cast<_TYPE_TO>(p));
46 #endif
47  return static_cast<_TYPE_TO*>(p);
48  };
49 
50 #define CHECKPTR_CAST(t,p) (::Gray::check_cast<t>(p))
51 }
52 
53 #endif
#define ASSERT(exp)
Definition: cDebugAssert.h:87
< The main namespace for all Core functions.
Definition: GrayCore.cpp:14
bool is_valid_cast(_TYPE_FROM *p)
Definition: PtrCast.h:27
_TYPE_TO * check_cast(_TYPE_FROM *p)
Definition: PtrCast.h:38