What is the curiously recurring template pattern (CRTP)?

前端 未结 5 1849
小鲜肉
小鲜肉 2020-11-21 11:27

Without referring to a book, can anyone please provide a good explanation for CRTP with a code example?

5条回答
  •  猫巷女王i
    2020-11-21 12:04

    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
    

提交回复
热议问题