Created
June 27, 2017 19:26
-
-
Save csullivan/8ce2311fa72cdc947958b3db786ac54d to your computer and use it in GitHub Desktop.
Compile time polymorphism: avoiding the short commings of virtual functions with the curiously recursive template pattern.
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> | |
class Base { | |
public: | |
Base() { ; } | |
~Base() { ; } | |
}; | |
template <typename Derived> | |
class Base_CRTP : public Base { | |
public: | |
auto get_member() { return static_cast<Derived*>(this)->member; } | |
}; | |
class ChildA : public Base_CRTP<ChildA> { | |
public: | |
float member = 3.14159; | |
}; | |
class ChildB : public Base_CRTP<ChildB> { | |
public: | |
int member = 42; | |
}; | |
int main() { | |
ChildA a_child; | |
ChildB b_child; | |
std::cout << a_child.get_member() << " " << b_child.get_member() << std::endl; | |
return 0; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment