Skip to content

Instantly share code, notes, and snippets.

@gonsolo
Created April 12, 2021 15:56
Show Gist options
  • Save gonsolo/368d5a9ccc983904248aceb587b4b4a3 to your computer and use it in GitHub Desktop.
Save gonsolo/368d5a9ccc983904248aceb587b4b4a3 to your computer and use it in GitHub Desktop.
CRTP aka static polymorphism
#include <iostream>
// CRTP aka static polymorphism
using namespace std;
template<typename T> class Base {
public:
void bla() {
auto derived = static_cast<T&>(*this);
derived.laber();
}
};
class Derived: public Base<Derived> {
public:
void laber() { cout << "laber" << endl; }
};
class Derived2: public Base<Derived2> {
public:
void laber() { cout << "laber2" << endl; }
};
template<typename T>
void hurz(T* base) {
base->bla();
}
void crtp() {
auto base1 = new Derived();
hurz(base1);
auto base2 = new Derived2();
hurz(base2);
}
int main() {
crtp();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment