协变虚函数和智能指针

8 c++ templates virtual-functions smart-pointers covariance

在C++中,子类可以在覆盖虚函数时指定不同的返回类型,只要返回类型是原始返回类型的子类(并且两者都作为指针/引用返回).

是否有可能将此功能扩展到智能指针?(假设智能指针是一些模板类)

为了显示:

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?
};
Run Code Online (Sandbox Code Playgroud)

编辑:正如Konrad Rudolph所说,这不是直接可能的.但是,我运行这个方法:

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();
        }
};
Run Code Online (Sandbox Code Playgroud)

你会建议这样走吗?

Kon*_*lph 8

是否有可能将此功能扩展到智能指针?(假设智能指针是一些模板类)

否:C++不知道/允许协变或逆变模板.有类型之间没有任何关系Ptr<A>,并Ptr<B>,即使A从继承B.