从模板基类派生的类的隐式转换 [英] Implicit cast of class derived from template base class

查看:124
本文介绍了从模板基类派生的类的隐式转换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个隐式转换,模板和继承从模板类的问题。下面是我从我的项目中提取的,我已经忽略了一些类甚至是抽象的,但它不必这样。

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();
}

基本上,我有一个模板基类 Base ,我从中导出 Derived:public Base< B> 。然后我必须把它转换为Base的最常见的出现形式,它是 Base

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>.

我想我可以将一个从 Base 派生的对象隐式地转换为 Base B 源自 A 。我做错了什么,或者如何隐含地 ?这很重要,因为我需要在 Base 作为参数的方法中接受所有类型的Derived类。

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.

提前感谢。

推荐答案

这是不可能的。 Base< A> Base< B> A和B之间。

This is not possible. Base<A> has no relation to Base<B>, regardless of the relation between A and B.

这篇关于从模板基类派生的类的隐式转换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆