简体   繁体   English

std :: shared_ptr的多态性如何?

[英]How is std::shared_ptr polymorphic?

I'm developing some container class, which has similar idea: holding pointer inside. 我正在开发一些容器类,它具有类似的想法:在内部保存指针。

#include <iostream>

template<class T>
class Container
{
public:
    Container ( )
    {
         pointer = new T ( );
    }

    ~Container ( )
    {
        delete pointer;
    }

    T* operator->( )
    {
        return pointer;
    }
private:
     T* pointer;
};

struct Base
{
    virtual void who ( )
    {
        std::cout << "Base" << std::endl;
    }
};


struct Child : public Base
{
    virtual void who ( ) override
    {
        std::cout << "Child" << std::endl;
    }
};

void testContainer ( Container<Base> c )
{
    c->who ( );
}

void testSharedPtr ( std::shared_ptr<Base> s )
{
    s->who ( );
}

int main ( )
{
    Container<Child> child;
    std::shared_ptr<Child> sharedChild;

    testSharedPtr ( sharedChild );
    testContainer ( child );
}

This code fails to compile: error C2664: 'void test(Container<Base> &)' : cannot convert argument 1 from 'Container<Child>' to 'Container<Base> &' 此代码无法编译: error C2664: 'void test(Container<Base> &)' : cannot convert argument 1 from 'Container<Child>' to 'Container<Base> &'
However with std::shared_ptr<Base> , instead of Container , everything works fine. 但是使用std::shared_ptr<Base>而不是Container ,一切正常。 So question is: 所以问题是:
Is std::shared_ptr -like polymorphysm implementable? std::shared_ptr polymorphysm是否可以实现? Or is this feature, which was somehow hardcoded in C++? 还是此功能(在C ++中以某种方式进行了硬编码)? Sorry for my primitive language. 对不起,我的原始语言。

Implement the following constructor: 实现以下构造函数:

template<class Other,
         class = typename std::enable_if<std::is_convertible<Other*, T*>::value>::type>
Container(const Container<Other>& _Other) 
{
    pointer = _Other.pointer;
}

This constructor will only be enabled if Other* is convertible to T* , which is obviosly the case if T is the base class of Other . 仅当Other*可转换为T*时才启用此构造函数,如果TOther的基类,则情况明显。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM