Last active
August 29, 2015 14:15
-
-
Save Hebali/d9a74c8ebddc93fe45b0 to your computer and use it in GitHub Desktop.
RTTI type traits in C++
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
// RTTI Type Traits | |
// Example by Patrick Hebron | |
template <typename T> struct TypeTraits | |
{ | |
static const char* name() { return "TYPE_NAME"; } | |
}; | |
struct Base | |
{ | |
Base() {} | |
virtual ~Base() {} | |
virtual void testPrint() = 0; | |
virtual void testPrintTraitName() = 0; | |
}; | |
template <typename DerivedT> | |
struct BaseImpl : public Base | |
{ | |
BaseImpl() {} | |
}; | |
#define DECLARE_DERIVED_TYPE(Type,Symbol) \ | |
template<> struct TypeTraits<struct Type> \ | |
{ \ | |
typedef Type type; \ | |
static const char* name() { return Symbol; } \ | |
}; \ | |
struct Type : public BaseImpl<Type> \ | |
DECLARE_DERIVED_TYPE( Foo, "FOO_TYPE" ) | |
{ | |
Foo() {} | |
void testPrint() { std::cout << "FOO::testPrint()" << std::endl; }; | |
void testPrintTraitName() { std::cout << TypeTraits<Foo>::name() << std::endl; }; | |
void testFoo() { std::cout << "FOO::testFoo()" << std::endl; }; | |
}; | |
DECLARE_DERIVED_TYPE( Bar, "BAR_TYPE" ) | |
{ | |
Bar() {} | |
void testPrint() { std::cout << "BAR::testPrint()" << std::endl; }; | |
void testPrintTraitName() { std::cout << TypeTraits<Bar>::name() << std::endl; }; | |
void testBar() { std::cout << "BAR::testBar()" << std::endl; }; | |
}; | |
int main(int argc, const char * argv[]) | |
{ | |
using namespace std; | |
Foo* aFoo = new Foo(); | |
Bar* aBar = new Bar(); | |
Base* aFooBaseCast = aFoo; | |
Base* aBarBaseCast = aBar; | |
aFoo->testPrint(); | |
aFoo->testPrintTraitName(); | |
aFoo->testFoo(); | |
cout << endl; | |
aBar->testPrint(); | |
aBar->testPrintTraitName(); | |
aBar->testBar(); | |
cout << endl; | |
aFooBaseCast->testPrint(); | |
aFooBaseCast->testPrintTraitName(); | |
cout << endl; | |
aBarBaseCast->testPrint(); | |
aBarBaseCast->testPrintTraitName(); | |
cout << endl; | |
delete aFoo; | |
delete aBar; | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment