带模板类的C ++多态克隆。不能在函数中使用克隆对象作为参数

时间:2015-08-26 10:36:29

标签: c++ templates arguments polymorphism clone

我有一个模板类Specie< T>,它派生自基类Animal。我创建了一个指向Animal的指针向量,以便在同一个向量中存储不同类型的对象Specie<T>。 T可以是狗,猫等...

现在我想在模板化函数中使用向量的某个元素作为参数。我为不同的模板参数T编写了函数的不同特化,因此每个Specie<T>的行为都不同。为了从向量中获取每个对象的正确类型,我使用了多态克隆。它运行良好,我得到了正确类型的对象Specie<T>(参见下面的非常简短的测试)。但是,当我想使用向量的元素作为模板化函数的参数时,它不起作用。

// Base class
class Animal{

 public:
  virtual ~Animal() {}

  virtual Animal *clone() = 0;
  virtual void action() = 0;

};


// Specific types of animals. Forward declaration
class Dog;
class Cat;



// Templated derived class Specie
template <class T>
class Specie : public Animal{

public:
    Specie<T> *clone();

    void action();

};





template <class T>
Specie<T> * Specie<T>::clone() {

   std::cout << "Cloning a Specie<T>" << std::endl;
   return new Specie<T>(*this);

}



// Specialization of templated function action() for Dog
template <>
void Specie<Dog>::action(){

  std::cout << "Wouaf !" << std::endl;

}


// Specialization of templated function action() for Cat
template <>
void Specie<Cat>::action(){

  std::cout << "Miaouuu !" << std::endl;

}




class Interaction{

public:

  template <class T1>
  static void DoSomething(Specie<T1>);

};



// Specialization of templated function DoSomething() for Dog
template <>
void Interaction::DoSomething(Specie<Dog> obj){

std::cout << "Interact with Dog !" << std::endl;

}


// Specialization of templated function DoSomething() for Cat
template <>
void Interaction::DoSomething(Specie<Cat> obj){

std::cout << "Interact with Cat !" << std::endl;

}




int main(){


 Specie<Cat> HelloKitty;
 Specie<Dog> Bobby;

 Animal *Dingo = new Specie<Dog>();

 Animal *Tom = new Specie<Cat>();

// cloning Dingo
 Animal *UnknownAnimal = Dingo->clone();

// We check the type is correct after cloning
 UnknownAnimal->action();

// We check that DoSomething recognizes correctly the type of objects
// and uses the proper specialization
 Interaction::DoSomething(Bobby);
 Interaction::DoSomething(HelloKitty);




// Vector of pointers to Animals
 std::vector<Animal *> myanimals;

// We add an object of type Specie<Dog> and an object
// of type Specie<Cat> to the vector

 myanimals.push_back(&Bobby);
 myanimals.push_back(&HelloKitty);



 Animal *UnknownAnimal2 = myanimals[1]->clone();

// We check the type is correct after cloning
 UnknownAnimal2->action();



// NOW WE TRY TO USE THE ELEMENT FROM VECTOR AS ARGUMENT OF 
// SPECIALIZED FUNCTION. DOES NOT WORK.
 Interaction::DoSomething(*(myanimals[0]->clone()));



  return 0;
}
  

错误:没有函数模板的实例“Interaction :: DoSomething”   匹配参数列表

     

参数类型是:(动物)交互:: DoSomething(*(myanimals [0] - &gt; clone()));

我的代码有什么问题?提前谢谢!

1 个答案:

答案 0 :(得分:0)

您正在调用基类函数virtual Animal *clone() = 0;,它似乎总是返回Animal

函数重载在编译时工作,并且不能根据参数的动态类型更改调用。为此,您需要虚拟函数调用。