Created
December 21, 2015 16:06
-
-
Save krysseltillada/978781f0045605ce8594 to your computer and use it in GitHub Desktop.
Run Time Type Identification (RTTI)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
#include <vector> | |
#include <typeinfo> | |
class Base { | |
public: | |
virtual ~Base () { } /// we need to defined this as virtual for dynamic type destructors | |
}; | |
class D1 : public Base { | |
public: | |
D1 () = default; | |
D1 (const std::string &s) : str (s) { } | |
std::string str; // test val for RTTI | |
virtual ~D1 () { } // this will override the method for Base | |
}; | |
class D2 : public Base { | |
public: | |
D2 () = default; | |
D2 (const char &cc) : c(cc) { } | |
char c; | |
virtual ~D2 () { } /// the same for D1 | |
}; | |
class D3 : public Base { | |
public: | |
D3 () = default; | |
D3 (const double &d) : dd (d) { } | |
double dd; | |
virtual ~D3 () { } | |
}; | |
class TypeClass { | |
public: | |
~ TypeClass () { | |
for (std::size_t s = 0; s != vtable.size (); ++s) | |
delete vtable[s]; | |
} | |
TypeClass &pushTypes (Base *b) { /// push types that are related to base | |
vtable.push_back (b); | |
return *this; | |
} | |
TypeClass &extract (std::vector <D1> &d1, | |
std::vector <D2> &d2, | |
std::vector <D3> &d3) { | |
for (std::size_t i = 0; i != vtable.size (); ++i) { | |
if (typeid (*vtable[i]) == typeid (D1)) { /// if this element is same as D1 then push the type in a specified vector | |
d1.push_back ( *dynamic_cast <D1 *> (vtable[i])); /// casts base into a D1 | |
} | |
else if (typeid (*vtable[i]) == typeid (D2)) { // if this element is same as D2 then | |
d2.push_back ( *dynamic_cast <D2 *> (vtable[i])); // casts base into a D2 | |
} | |
else if (typeid (*vtable[i]) == typeid (D3)) { /// if this element is same as D3 then | |
d3.push_back ( *dynamic_cast <D3 *> (vtable[i])); /// casts base into a D3 | |
} | |
} | |
return *this; | |
} | |
private: | |
std::vector <Base *> vtable; | |
}; | |
int main () | |
{ | |
std::vector <D1> d1vec; | |
std::vector <D2> d2vec; | |
std::vector <D3> d3vec; | |
TypeClass d; | |
d.pushTypes(new D1("0x12f")); | |
d.pushTypes(new D3(12.3)); | |
d.pushTypes(new D2('a')); | |
d.pushTypes(new D1 ("0x14f")); | |
d.extract(d1vec, d2vec, d3vec); | |
for (std::size_t i = 0; i != d1vec.size (); ++i) | |
std::cout << d1vec[i].str << std::endl; | |
for (std::size_t a = 0; a != d2vec.size (); ++a) | |
std::cout << d2vec[a].c << std::endl; | |
for (std::size_t v = 0; v != d3vec.size (); ++v) | |
std::cout << d3vec[v].dd << std::endl; | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment