[英]Is the only way to “polymorphically” declare a member of a non-specialized template type, by defining a base class?
Suppose we have a templated class, 假设我们有一个模板化的类,
template<typename Type>
class Container {};
Of course, we can't do this: 当然,我们不能这样做:
struct Foo
{
Container _container;
}
But what if we wanted to do something like it? 但是,如果我们想做类似的事情怎么办? Is the only way to do this, to define a base class,
这是定义基类的唯一方法,
class ContainerBase {};
template<typename Type>
class Container : public ContainerBase {};
and store a pointer, like below? 并存储一个指针,如下所示?
struct Foo
{
ContainerBase* _container;
}
It's simple enough, but it feels weird to have to add a base class solely for that reason, when it seems the compiler should have enough information to imply a set of related specializations. 这很简单,但是仅出于这个原因而不得不添加基类,这似乎很奇怪,因为看起来编译器应该具有足够的信息来暗示一组相关的专业知识。 Of course, regardless
_container
needs to be a pointer, else Foo
couldn't resolve to a static size, but 当然,无论
_container
需要成为指针,否则Foo
都无法解析为静态大小,但是
struct Foo
{
Container* _container;
}
doesn't work either. 也不起作用。
it seems the compiler should have enough information to imply a set of related specializations.
似乎编译器应该具有足够的信息来暗示一组相关的专业知识。
Nope. 不。 Template specializations are totally unrelated except in name, and the name of a type has essentially no bearing on runtime operation.
模板的专门性完全不相关,只是名称不同,类型的名称与运行时操作基本无关。 Specializations of a given template usually share a (mostly) common interface, but they could just as well be completely different.
给定模板的专业化通常共享(主要是)通用接口,但是它们也可能完全不同。
Adding a base class is essential if you want to relate between the specializations. 如果要在各专业之间建立联系,则必须添加基类。 And if they share so much in common, factoring that functionality into the base is a pretty great idea.
如果它们有很多共同点,那么将功能纳入基础是一个不错的主意。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.