CRTP (Curious Recursive Template Pattern)

//crtp.h
#ifndef CRTP_H
#define CRTP_H
template 
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(this) -> implement();
    }

    static void static_base_func() {
        T::static_impl_func();
    }
};

//tip 4 public extends
class Deriv1 : public Base
{
//tip 3 public for implementation
public:
    void implement();
    static void static_impl_func();

};
#endif
//crtp.cpp
#include"crtp.h"
#include

void Deriv1::implement(){
    std::cout<<"Implement Member function in Deriv1"<
#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;
}

你可能感兴趣的:(CRTP (Curious Recursive Template Pattern))