C++ Curiously Recurring Template Prattern(CRTP)例程

简单介绍和例子请参考: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....

 

posted @ 2017-09-26 12:40  horsetail  阅读(299)  评论(0编辑  收藏  举报