它取决于模板用于传递类型的用途。如果你指的是标准容器(例如std::vector
,std::map
等),那么答案是否定的。在std::vector<Animal>
和std::vector<Dog>
之间没有任何关系,即使在你的阶级层次结构中,狗来源于动物。
你不能把一个Dog
在std::vector<Animal>
... C++使用拷贝语义,你会在所谓招致“slicing”这意味着你的Dog
实例将失去,是不是也存在于基本Animal
类中的任何成员。
但是,通常当模板以不同的方式使用该类型,因此可以接受派生类的实例时,这当然是有可能的。例如,在以下代码中,可以使用类型实例化模板MethodCaller
,但使用派生类型的实例并正确处理后期绑定调度。这是可能的,因为MethodCaller
实例仅保留引用并且不会生成该对象的副本。
#include <stdio.h>
template<typename T>
struct MethodCaller
{
T& t;
void (T::*method)();
MethodCaller(T& t, void (T::*method)())
: t(t), method(method)
{}
void operator()() { (t.*method)(); }
};
struct Animal { virtual void talk() = 0; };
struct Dog : Animal { virtual void talk() { printf("Bark\n"); } };
struct Cat : Animal { virtual void talk() { printf("Meow\n"); } };
struct Crocodile : Animal { virtual void talk() { printf("??\n"); } };
void makenoise(Animal *a)
{
MethodCaller<Animal> noise(*a, &Animal::talk);
noise(); noise(); noise();
}
int main()
{
Dog doggie;
Cat kitten;
Crocodile cocco;
makenoise(&doggie);
makenoise(&kitten);
makenoise(&cocco);
}
也可以根据需要实现Stack
类...
#include <vector>
template<typename T>
struct Stack
{
std::vector<T *> content;
~Stack()
{
for (int i=0,n=content.size(); i<n; i++)
delete content[i];
}
template<class S>
void push(const S& s)
{
content.push_back(new S(s));
}
template<class S>
S pop()
{
S result(dynamic_cast<S&>(*content.back()));
content.pop_back();
return result;
}
private:
// Taboo
Stack(const Stack&);
Stack& operator=(const Stack&);
};
int main()
{
Dog doggie;
Cat kitten;
Crocodile cocco;
Stack<Animal> s;
s.push(doggie);
s.push(kitten);
s.push(cocco);
Crocodile cocco2 = s.pop<Crocodile>();
Cat kitten2 = s.pop<Cat>();
Dog doggie2 = s.pop<Dog>();
}
注意的是,在实现我使用的std::vector
保持指针动物,因此避免切割问题。我一直在使用模板方法来接受推送调用中的派生类型。
还要注意的是弹出的动物时,你必须提供什么是类,如果它是一个错误的(例如,你蹦出一个Crocodile
当栈顶元素是Dog
),你会在运行时得到一个bad_cast
例外。
对于指针容器,我只能推荐使用Boost指针容器作为基础。它就像智能指针一样,但是对于多个对象以及STL所期望的通常混合的属性。 – 2011-03-20 16:33:00