Implicit cast of class derived from template base class

不问归期 提交于 2019-12-23 10:57:07

问题


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.


回答1:


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




回答2:


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.



来源:https://stackoverflow.com/questions/6238544/implicit-cast-of-class-derived-from-template-base-class

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!