美文网首页
CRTP (Curious Recursive Template

CRTP (Curious Recursive Template

作者: 小雪球的学习笔记 | 来源:发表于2018-06-26 11:52 被阅读0次
//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;
}

相关文章

网友评论

      本文标题:CRTP (Curious Recursive Template

      本文链接:https://www.haomeiwen.com/subject/vxmuyftx.html