gpt4 book ai didi

c++ - 衍生出奇怪的重复模板和协方差

转载 作者:可可西里 更新时间:2023-11-01 17:56:57 26 4
gpt4 key购买 nike

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

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

// ...
};

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

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 的继承树的结果。此外,将返回类型 (T*) 替换为 (Base*) 也可以编译。但是,我想知道是否有保留上述语义的解决方法。

最佳答案

一个不太好的解决方法。

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<>而不是 static如果您觉得它更安全。

关于c++ - 衍生出奇怪的重复模板和协方差,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17201268/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com