-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathconstexpr_is_derived.cpp
64 lines (47 loc) · 958 Bytes
/
constexpr_is_derived.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
#include <typeinfo>
#include <iostream>
// Does not work with POD types
// Does not work if types are not polymorphic
template <class C, class P>
bool IsDerivedFrom()
{
try
{
C* derivedClassObject;
P* parentClassObject = dynamic_cast<P*>(derivedClassObject);
}
catch (std::bad_cast)
{
return false;
}
// Dynamic cast one into another - if it is then ok, if not return std::bad_cast
// Returns true when C is derived from P
return false; //return a helper
}
template<typename D, typename B>
class IsDerivedFromHelper
{
class No {};
class Yes { No no[3]; };
static Yes Test(B*);
static No Test(...);
public:
enum { Is = sizeof(Test(static_cast<D*>(0))) == sizeof(Yes) };
};
template <class C, class P>
bool IsDerivedFromExample() {
return IsDerivedFromHelper<C, P>::Is;
}
class A
{
int aMember;
};
class B
{
int bMember;
};
int main()
{
std::cout << IsDerivedFromExample<A, B>() << "\n";
return 0;
}