Created
May 28, 2019 22:48
-
-
Save RootKiller/e99acf19f550992e51694ca524ff9514 to your computer and use it in GitHub Desktop.
Simple RTTI replacement (C++)
This file contains 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 <stdio.h> | |
struct type_id_t | |
{ | |
const type_id_t *const parent; | |
const char *const name; | |
}; | |
struct parent_t | |
{ | |
inline static const type_id_t type_descriptor { nullptr, "parent_t" }; | |
virtual bool inherits_from(const type_id_t &t) const | |
{ | |
return (&type_descriptor == &t); | |
} | |
virtual const type_id_t &get_type_descriptor() const | |
{ | |
return type_descriptor; | |
} | |
template <typename T> | |
bool is_a() const | |
{ | |
return inherits_from(T::type_descriptor); | |
} | |
template <typename T> | |
T *safe_cast() | |
{ | |
if (is_a<T>()) { | |
return static_cast<T *>(this); | |
} | |
return nullptr; | |
} | |
}; | |
#define STRINGIZE2(x) #x | |
#define STRINGIZE(x) STRINGIZE2(x) | |
#define SUPER_CLASS(self_t, parent_t)\ | |
inline static const type_id_t type_descriptor { &parent_t::type_descriptor, STRINGIZE(self_t) }; \ | |
using super_t = parent_t; \ | |
\ | |
virtual bool inherits_from(const type_id_t &t) const override \ | |
{ \ | |
if (&type_descriptor == &t) { \ | |
return true; \ | |
} \ | |
return super_t::inherits_from(t); \ | |
} \ | |
virtual const type_id_t &get_type_descriptor() const override \ | |
{ \ | |
return type_descriptor; \ | |
} | |
struct proxy_t : public parent_t | |
{ | |
SUPER_CLASS(proxy_t, parent_t); | |
}; | |
struct test_t : public proxy_t | |
{ | |
SUPER_CLASS(test_t, proxy_t); | |
alignas(16) int main; | |
int main2; | |
int main3; | |
int main4; | |
}; | |
int main() { | |
test_t *a = new test_t(); | |
test_t *b = new test_t(); | |
test_t *c = new test_t(); | |
parent_t *p = a; | |
printf("%s / %i / %i / %i\n", a->get_type_descriptor().name, a->is_a<proxy_t>(), a->is_a<parent_t>(), | |
p->is_a<test_t>()); | |
const type_id_t *type = &a->get_type_descriptor(); | |
while (type) { | |
printf("%s\n", type->name); | |
type = type->parent; | |
} | |
type = &a->safe_cast<proxy_t>()->get_type_descriptor(); | |
while (type) { | |
printf("%s\n", type->name); | |
type = type->parent; | |
} | |
// printf("%lX\n", a); | |
// printf("%lX\n", b); | |
// printf("%lX\n", c); | |
delete a; | |
delete b; | |
delete c; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment