Without referring to a book, can anyone please provide a good explanation for CRTP
with a code example?
Just as note:
CRTP could be used to implement static polymorphism(which like dynamic polymorphism but without virtual function pointer table).
#pragma once
#include
template
class Base
{
public:
void method() {
static_cast(this)->method();
}
};
class Derived1 : public Base
{
public:
void method() {
std::cout << "Derived1 method" << std::endl;
}
};
class Derived2 : public Base
{
public:
void method() {
std::cout << "Derived2 method" << std::endl;
}
};
#include "crtp.h"
int main()
{
Derived1 d1;
Derived2 d2;
d1.method();
d2.method();
return 0;
}
The output would be :
Derived1 method
Derived2 method