Skip to content

Instantly share code, notes, and snippets.

@csullivan
Created June 27, 2017 19:26
Show Gist options
  • Save csullivan/8ce2311fa72cdc947958b3db786ac54d to your computer and use it in GitHub Desktop.
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.
#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