派生出奇怪的重复模板和协方差 [英] Derived curiously recurring templates and covariance

查看:150
本文介绍了派生出奇怪的重复模板和协方差的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个克隆派生类的基类:

Suppose I have a base class which cloning of derived classes:

class Base
{
    public:
        virtual Base * clone()
        {
            return new Base();
        }

        // ...
};



我有一组派生类,使用奇怪的重复模板模式实现:

I have a set of derived classes which are implemented using a curiously recurring template pattern:

template <class T>
class CRTP : public Base
{
    public:
        virtual T * clone()
        {
            return new T();
        }

        // ...
};

我试图从这样得出:

class Derived : public CRTP<Derived>
{
    public:
        // ...
};

我遇到的编译错误:

error C2555: 'CRTP<T>::clone': overriding virtual function return type differs and is not covariant from 'Base::clone'

我意识到这可能是编译器在实例化CRTP时不完全知道Derived的继承树的结果。此外,用(Base *)替换返回类型(T *)也会编译。但是,我想知道是否有一个保留上述语义的工作。

I realize this is probably a result of the compiler not fully knowing the inheritance tree for Derived when instantiating CRTP. Furthermore, replacing the return type (T*) with (Base*) also compiles. However, I would like to know if there is a work around which retains the above semantics.

推荐答案

不那么漂亮解决方法。

class Base
{
    protected:
        virtual Base * clone_p()
        {
            return new Base();
        }
};


template <class T>
class CRTP : public Base
{
    protected:
        virtual CRTP* clone_p()
        {
            return new T;
        }
    public:
        T* clone()
        {
            CRTP* res = clone_p();
            return static_cast<T*>(res);
        }
};


class Derived : public CRTP<Derived>
{
    public:
};

使用 dynamic_cast<> code> static 如果你觉得它更安全。

Use dynamic_cast<> instead of static if you feel it's safer.

这篇关于派生出奇怪的重复模板和协方差的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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