我有从具有虚函数的基类继承的派生类。我使用智能指针(shared_ptr)来创建对象,因为我希望将对象附加到向量中。但是我注意到我的代码在处理对象以执行某些任务时是重复的,所以我认为模板可以成为改进我的代码的解决方案。这是我迄今为止的尝试(不是确切的代码,简化):
class Base{
public:
virtual ~Base(){}
virtual void display_message() = 0;
};
class DerivedA : public Base{
DerivedA(){}
};
class DerivedB : public Base{
DerivedB(){}
};
//THE template-
//<hold the smart pointer that points to different derived objects>
template<typename T1>
class HandleInstances{
private:
vector<T1> ObjectVector;
//the iterator
T1 sp_base;
public:
HandleInstance(const T1 & sp){
sp_base = sp; // set smart pointer
}
//somefunctions
//this is what i need to figure out
void AddToVector(){
ObjectVector.push_back(sp_base(new 'The derived class') );
}
};
AddToVector 函数是这里的问题。为了添加一个对象的元素,我必须这样做 push_back("the smart pointer"(new "the class"));。我如何让模板接受类(不是对象)并将其实现到 push_back() 的函数中?