作者热门文章
- android - RelativeLayout 背景可绘制重叠内容
- android - 如何链接 cpufeatures lib 以获取 native android 库?
- java - OnItemClickListener 不起作用,但 OnLongItemClickListener 在自定义 ListView 中起作用
- java - Android 文件转字符串
假设我有一个克隆派生类的基类:
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/
考虑以下代码: #include using namespace std; class Base { public: int foo; }; class Derived : public B
我是一名优秀的程序员,十分优秀!