//crtp.h
#ifndef CRTP_H
#define CRTP_H
template <typename T>
class Base
{
public:
//tip 1 interface have to in header, otherwise can't link in usage
void interface() {
//tip 2 static cast this to T*
static_cast<T*>(this) -> implement();
}
static void static_base_func() {
T::static_impl_func();
}
};
//tip 4 public extends
class Deriv1 : public Base<Deriv1>
{
//tip 3 public for implementation
public:
void implement();
static void static_impl_func();
};
#endif
//crtp.cpp
#include"crtp.h"
#include<iostream>
void Deriv1::implement(){
std::cout<<"Implement Member function in Deriv1"<<std::endl;
}
//tip 4 no static in cpp file even it is static method
void Deriv1::static_impl_func(){
std::cout<<"Implement Static function in Deriv1"<<std::endl;
}
#include"crtp.h"
int main(){
//declare deriv class directly
Deriv1 bp = Deriv1();
// can call interface in base class
bp.interface();
bp.static_base_func();
return 0;
}