-
Notifications
You must be signed in to change notification settings - Fork 160
/
typeid.cpp
112 lines (87 loc) · 2.51 KB
/
typeid.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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
/*
# typeid
Get runtime type of variables.
Can be done for both types and variables of the type.
Returns objects of `type_info`
# type_info
Type returned by `typeid`.
*/
#include "common.hpp"
int main() {
/*
typeid returns `type_info`.
However copy and assign for type_info are private,
so the following fail.
*/
{
//std::type_info t = typeid(int);
//std::type_info t(typeid(int));
}
/*
type_info implements `==` and `!=`.
typeid's of different types are always different.
*/
{
int i, i1;
int& ia = i;
assert(typeid(i) == typeid(int) );
assert(typeid(ia) == typeid(int&));
assert(typeid(i) == typeid(i1) );
}
// Works differently for virtual and non virtual classes!
// http://stackoverflow.com/questions/11484010/c-typeid-used-on-derived-class-doesnt-return-correct-type
{
class C {};
class D : public C {};
C c;
D d;
C *dp = &d;
assert(typeid(C) == typeid(c) );
assert(typeid(*dp) == typeid(C) );
assert(typeid(*dp) != typeid(D) );
class PolyBase {
void virtual f() {};
};
class PolyDerived : public PolyBase {
void virtual f() {};
};
PolyDerived pd;
PolyBase *pdp = &pd;
assert(typeid(*pdp) == typeid(PolyDerived));
}
/*
# name
`name`: return a string representation of the type.
The exact string is implementation defined.
`name()` is implementation defined.
On GCC, you can demangle with `__cxa_demangle`:
http://stackoverflow.com/questions/4465872/why-typeid-name-returns-weird-characters-using-gcc
*/
{
std::cout << "typeid(int).name() = " << typeid(int).name() << std::endl;
}
/* The return value is calculated at runtime. */
{
class Base {
public:
virtual void f() {}
};
class Derived : public Base {
public:
virtual void f() {}
};
Derived d;
Base *bp = &d;
// The mangled Derived ID is output.
assert(typeid(*bp).name() == typeid(Derived).name());
}
// before: http://stackoverflow.com/questions/8682582/what-is-type-infobefore-useful-for
// hash_code: return a size_t hash of the type
/*
# type_index
Wrapper around type_info that allows copy and assign.
*/
{
std::type_index t = typeid(int);
}
}