从模板基类派生的类的隐式转换

发布于 2024-11-14 06:48:51 字数 666 浏览 3 评论 0原文

我遇到了隐式转换、模板和模板类继承的问题。以下是我从我的项目中提取的内容,我遗漏了一些类甚至是抽象的,但这与案例无关。

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

风和你 2024-11-21 06:48:51

这是不可能的。无论 A 和 B 之间的关系如何,BaseBase没有关系。

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

动次打次papapa 2024-11-21 06:48:51

Base 不一定需要与 Base 有关系。这与 Derived 没有任何关系。如果你想强制建立这样的关系,你将需要一个模板化的构造函数。

template <typename T>
class Base
{
    template <typename TOther>
    Base(const TOther& that)
    {
        // ...
    }
    // ...
};

显然,实现必须取决于Base 的实际实现。请注意,此构造函数不会替代普通的复制构造函数。

Base<B> does not necessarily need to have a relation to Base<A>. This doesn't have anything to do with Derived. If you want to force such a relation, you're going to need a templated constructor.

template <typename T>
class Base
{
    template <typename TOther>
    Base(const TOther& that)
    {
        // ...
    }
    // ...
};

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文