具有多态模板参数的多态模板类 [英] Polymorphic templated classes with polymorphic template parameters
问题描述
在一个简单的设计中,类B多态地继承了类A.
模板类Base<T>
具有一个T*
成员,该成员用于进一步的操作. Derived<T>
是Base<T>
的多态继承.
允许这种对象创建的语法是什么?
In a simplistic design, a class B inherits a class A polymorphically.
A templated class, Base<T>
has a T*
member that is used for further operations. A Derived<T>
inherits from Base<T>
polymorphically.
What would be the syntax that allows this kind of object creation:
Base<A>* a = new Derived<B>();
为进一步参考,我使用的代码如下(当然,转换不会成功):
For further reference, the code I used looks like this (of course, the conversion does not succeed):
class A
{
public:
A()
{
cout<< " A ";
}
virtual void one()
{
cout<<" 1 ";
}
};
class B: public A
{
public:
B()
{
cout << " B ";
}
void one()
{
cout << " 2 ";
}
};
template <class T>
class Base
{
public:
T* thing;
Base()
{
cout<<"Base";
thing = new T;
}
template <class S>
Base(Base<S>* obj)
{
thing = obj->thing;
}
virtual void poly(){ thing->one();}
};
template <class T>
class Derived : public Base<T>
{
public:
Derived()
{
cout << "DERIVED ";
}
virtual void poly(){
};
int main(int argc, char** argv)
{
//Base<A>* a = (new Derived<B>());
return 0;
}
为代码简洁起见,故意省略了虚拟析构函数和适当的内存管理.
Virtual destructors and proper memory management omitted on purpose for code brevity.
EDIT :此构造的唯一目的是将例如BaseTemplated<BasePolymorphic>*
个指针的列表放在一起,而不是将BaseTemplated<Derived1>
到BaseTemplated<DerivedN>
用于a的所有N个子类.基本的多态类.
EDIT : the sole purpose of this construction would be to keep, say, a list of BaseTemplated<BasePolymorphic>*
pointers together, and not use BaseTemplated<Derived1>
to BaseTemplated<DerivedN>
for all N subclasses of a base, polymorphic class.
推荐答案
首先,告诉我何时进入简单化"部分.
First, tell me when we get to the "simplistic" part.
剥离所有模板的一半内容,仅专注于您要进行多态处理的部分).最终,您将获得不同的类Base<A>
和Base<B>
. (后者是通过Derived<B>
的推导得出的.)
Peel back all half of the templates to just concentrate on the part you're trying to polymorph). Eventually you have distinct classes Base<A>
and Base<B>
. (the latter through derivation of Derived<B>
).
这两个继承都不来自其各自的模板参数.因此,A
与B
的关系(分层或其他方式)是不相关的. Base<A>
和Base<B>
是不同的且无关的,因此您尝试按原样进行的操作无效.实际上,即使 did 分别从A
和B
继承,您所希望的最好的情况就是A*
指针,您在示例中没有使用该指针.
Neither of these inherit from their respective template parameters. Therefore the relationship (hierarchical or otherwise) of A
to B
is irrelevant. Base<A>
and Base<B>
are distinct and unrelated, and therefore what you're trying to do as-writen cannot work. In fact, even if the did inherit from a A
and B
respectively, the very best you could hope for is an A*
pointer, which you aren't using in your sample.
如果没有另外显示,我会很高兴地删除它们,因为我真的很好奇.
And I'll gladly delete this if shown otherwise, because I'm genuinely curious.
这篇关于具有多态模板参数的多态模板类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!