What is the curiously recurring template pattern (CRTP)?

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

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

5条回答
  •  我在风中等你
    2020-11-21 12:17

    CRTP is a technique to implement compile-time polymorphism. Here's a very simple example. In the below example, ProcessFoo() is working with Base class interface and Base::Foo invokes the derived object's foo() method, which is what you aim to do with virtual methods.

    http://coliru.stacked-crooked.com/a/2d27f1e09d567d0e

    template 
    struct Base {
      void foo() {
        (static_cast(this))->foo();
      }
    };
    
    struct Derived : public Base {
      void foo() {
        cout << "derived foo" << endl;
      }
    };
    
    struct AnotherDerived : public Base {
      void foo() {
        cout << "AnotherDerived foo" << endl;
      }
    };
    
    template
    void ProcessFoo(Base* b) {
      b->foo();
    }
    
    
    int main()
    {
        Derived d1;
        AnotherDerived d2;
        ProcessFoo(&d1);
        ProcessFoo(&d2);
        return 0;
    }
    

    Output:

    derived foo
    AnotherDerived foo
    

提交回复
热议问题