Created
April 12, 2021 15:56
-
-
Save gonsolo/368d5a9ccc983904248aceb587b4b4a3 to your computer and use it in GitHub Desktop.
CRTP aka static polymorphism
This file contains 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> | |
// 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