Created
July 27, 2018 00:12
-
-
Save bit-hack/8362cc2a066d7044c9b54be9e0cfa22a to your computer and use it in GitHub Desktop.
Very simple 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 <assert.h> | |
| struct rtti_t { | |
| template <typename type_t> | |
| bool is_a() const { | |
| return _tag == type_t::tag; | |
| } | |
| template <typename type_t> | |
| type_t & cast() { | |
| assert(is_a<type_t>()); | |
| return *static_cast<type_t*>(this); | |
| } | |
| template <typename type_t> | |
| const type_t & cast() const { | |
| assert(is_a<type_t>()); | |
| return *static_cast<const type_t*>(this); | |
| } | |
| protected: | |
| rtti_t(const int tag) | |
| : _tag(tag) | |
| { | |
| } | |
| const int _tag; | |
| }; | |
| struct test1_t : public rtti_t { | |
| test1_t() : rtti_t(tag) {} | |
| int foo; | |
| static const int tag; | |
| }; | |
| struct test2_t : public rtti_t { | |
| test2_t() : rtti_t(tag) {} | |
| static const int tag; | |
| }; | |
| int main() { | |
| rtti_t *x = new test1_t; | |
| if (x->is_a<test2_t>()) { | |
| return 0; | |
| } | |
| x->cast<test1_t>().foo = 1; | |
| return 1; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment