从模板基类派生的类的隐式转换
我遇到了隐式转换、模板和模板类继承的问题。以下是我从我的项目中提取的内容,我遗漏了一些类甚至是抽象的,但这与案例无关。
class A {};
class B : public A {};
template <typename T> class Base {};
class Derived : public Base<B> {};
int main() {
Derived d;
Base<A>* base = new Derived();
}
基本上,我有一个模板基类 Base
,从中派生 Derived : public Base
。然后我必须将其转换为 Base 最常见的形式,即 Base
。
我本以为我可以将从 Base
派生的对象隐式转换为 Base
,因为 B
派生自 A
。我是否做错了什么或者我如何隐式地投射它?这很重要,因为我需要在 Base
方法中接受所有类型的派生类作为参数。
提前致谢。
I've got a problem with implicit casting, templates and inheritance from template classes. The following is what I extracted from my project, I have left out that some classes are even abstract, but it does not have to do with the case.
class A {};
class B : public A {};
template <typename T> class Base {};
class Derived : public Base<B> {};
int main() {
Derived d;
Base<A>* base = new Derived();
}
Basically, I have a template base class Base
that I derive Derived : public Base<B>
from. Then I have to cast it to the most general occuring form of Base, which is Base<A>
.
I would have thought that I can cast an Object deriving from Base<B>
to Base<A>
implicitly, as B
derives from A
. Am I doing something wrong or how could I cast that implicitly? This is important as I need to accept all types of Derived classes in a method of Base
as a parameter.
Thanks in advance.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这是不可能的。无论 A 和 B 之间的关系如何,
Base
与Base
都没有关系。This is not possible.
Base<A>
has no relation toBase<B>
, regardless of the relation between A and B.Base
不一定需要与Base
有关系。这与Derived
没有任何关系。如果你想强制建立这样的关系,你将需要一个模板化的构造函数。显然,实现必须取决于
Base
的实际实现。请注意,此构造函数不会替代普通的复制构造函数。Base<B>
does not necessarily need to have a relation toBase<A>
. This doesn't have anything to do withDerived
. If you want to force such a relation, you're going to need a templated constructor.Obviously, the implementation would have to depend on the actual implementation of
Base
. Note that this constructor doesn't substitute for the normal copy constructor.