簡單介紹和例子請參考:C++ 慣用法 CRTP 簡介
下面例子為兼顧CRTP和多型的例子。
#include <iostream> #include <vector> using namespace std; class Animal { public: virtual void say() const =0; virtual ~Animal() { } }; template<class T> class Animal_CRTP : public Animal { public: Animal_CRTP() { } void say() const { static_cast<const T*>(this)->say(); } }; class Cat : public Animal_CRTP<Cat> { public: void say() const { cout << "I am cat!miao...." << endl; } }; class Dog : public Animal_CRTP<Dog> { public: void say() const { cout << "I am dog!wang...." << endl; } }; class Dug : public Animal_CRTP<Dug> { public: void say() const { cout << "I am dug!gaga...." << endl; } }; int main(int argc, char** argv) { vector<Animal*> zoo; zoo.push_back(new Cat()); zoo.push_back(new Dog()); zoo.push_back(new Dug()); for (auto a : zoo) { a->say(); } return 0; }
執行結果:
I am cat!miao.... I am dog!wang.... I am dug!gaga....