协变虚拟函数和智能指针 [英] Covariant virtual functions and smart pointers
问题描述
在C ++中,子类可以在重写虚拟函数时指定不同的返回类型,只要该返回类型是原始返回类型的子类(并且两者均作为指针/引用返回)即可.
In C++, a subclass can specify a different return type when overriding a virtual function, as long as the return type is a subclass of the original return type (And both are returned as pointers/references).
是否可以将此功能扩展到智能指针?(假设智能指针是某些模板类)
Is it possible to expand this feature to smart pointers as well? (Assuming a smart pointer is some template class)
说明:
class retBase {...};
class retSub : public retBase {...};
class Base
{
virtual retBase *f();
};
class Sub : public Base
{
virtual retSub *f(); // This is ok.
};
class smartBase
{
virtual smartPtr<retBase> f();
};
class smartSub : public smartBase
{
virtual smartPtr<retSub> f(); // Can this be somehow acheived?
};
编辑:正如Konrad Rudolph所建议的那样,这不可能直接实现.但是,我遇到了这种方法:
As Konrad Rudolph suggested, this is not directly possible. However, I ran accross this method:
class smartBase
{
protected:
virtual retBase *f_impl();
public:
smartPtr<refBase> f()
{
return f_impl();
}
};
class smartSub : public smartBase
{
protected:
virtual retSub *f_impl();
public:
smartPtr<refSub> f()
{
return f_impl();
}
};
您建议这样做吗?
推荐答案
是否可以将此功能扩展到智能指针?(假设智能指针是某些模板类)
Is it possible to expand this feature to smart pointers as well? (Assuming a smart pointer is some template class)
否:C ++不知道/不允许协变或逆变模板.即使 A
继承自 B
,类型 Ptr< A>
和 Ptr< B>
之间也没有关系.
No: C++ doesn't know/allow covariant or contravariant templates. There's no relation between types Ptr<A>
and Ptr<B>
, even if A
inherits from B
.
这篇关于协变虚拟函数和智能指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!