如何将shared_ptr从一个父类强制转换为另一个父类?

时间:2017-10-16 15:45:14

标签: c++ inheritance shared-ptr smart-pointers

我正在重新使用我的游戏引擎来使用smart-pointers。我有一个Object类,一切都继承自。我有一个可渲染的GameObject,因此它继承自IRenderable(一个定义纯虚拟渲染函数的类),不继承自Object 。我有一个RenderSystem,它应该为场景中的所有IRenderable保留shared_ptr

我遇到的问题是如何将GameObject shared_ptr转换为RenderSystem的IRenderable?

我尝试过的想法:

  • RenderSystem使用GameObject的shared_ptr,但这不起作用,因为并非所有游戏对象都可以渲染。
  • 让IRenderable从Object继承,这应该允许我继承它。这意味着IRenderable不再是一个接口,因为Object包含其他功能。

这完全可以使用原始指针,因此,我觉得有一些方法可以通过智能指针实现相同的结果

示例:

// Object.h
class Object : public enable_shared_from_this<Object> { ... }
// GameObject.h
class GameObject : public Object { ... }
// MeshRenderer.h
class MeshRenderer : public GameObject, IRenderable { 
public:
    void initialize()
    {
         // Not able to cast Object to IRenderable
         RenderSystem::instance().addRenderable(getShared());

         // AND

         // Not able to cast Object to IRenderable

RenderSystem::instance().addRenderable(std::static_pointer_cast<IRenderable>(getShared()));
    }
}
// RenderSystem.h
class RenderSystem 
{
    std::list<std::shared_ptr<IRenderable>> m_renderables;
 public:
    void addRenderable(std::shared_ptr<IRenderable> ptr)
    {
       m_renderables.push_back(ptr);
    }
}

// main.cpp
...
auto meshRenderer = std::shared_ptr<MeshRenderer>();
...

2 个答案:

答案 0 :(得分:5)

您无法直接从$computerName = Get-Wmiobject Win32_ComputerSystem $computerOS = Get-Wmiobject Win32_OperatingSystem $computerHDD = Get-Wmiobject Win32_LogicalDisk -Filter drivetype=3 ForEach($HDD in $computerHDD){ $txtObject = New-Object PSObject -property @{ 'ComputerName' = $computerName.Name 'ComputerModel' = $computerName.Model 'SerialNumber' = $computerName.SerialNumber 'HDDSize' = "{0:N2}" -f ($HDD.Size/1GB) 'HDDFree' = "{0:P2}" -f ($HDD.FreeSpace/$HDD.Size) 'OS' = $computerOS.caption 'OS_type' = $computerOS.OSArchitecture 'User' = $computerName.UserName } } $txtObject | Select-Object ComputerName, ComputerModel, SerialNumber, HDDSize, HDDFree, OS, Os_type, User | Out-File "$PSSCriptRoot\computer_info.txt" -Append static_pointer_cast执行shared_ptr<Object>,因为这些类型不相关。

但是你可以转换为派生类型,然后允许隐式转换为shared_ptr<IRenderable>

shared_ptr<IRenderable>

执行从第一个基类到派生类型的显式转换,然后隐式转换为第二个基类型。这是静态允许的,因为已知派生类型与两个碱基相关,但不相关碱基之间的直接转换是不可能的。

答案 1 :(得分:3)

像这样:

#include <memory>

// everything is an Object - yuk, but ok, if you wish...
struct Object : std::enable_shared_from_this<Object>
{
};

struct GameObject : Object
{

};

struct IRenderable
{
    virtual void render() {};
};

struct RederableGameObject : GameObject, IRenderable
{
    auto as_shared_renderable() -> std::shared_ptr<IRenderable>
    {
        // builds a new shared pointer to IRenderable which
        // uses the same lifetime control block as me
        return std::shared_ptr<IRenderable>
        {
            this->shared_from_this(),   // where to get the control block
            this                        // what to point to
        };
    }
};

文档:

参见构造函数编号(8)

http://en.cppreference.com/w/cpp/memory/shared_ptr/shared_ptr

更新

以下是自由函数从任何对象获取正确的shared_pointer的起点,前提是它最终是从std::enable_shared_from_this

公开派生的
#include <memory>
#include <type_traits>

namespace notstd
{
    // stuff that I think *should be* std

    using namespace std;

    // a trait to determine whether class T is derived from template
    // Tmpl<...>

    template <typename T, template <class...> class Tmpl>
    struct is_derived_from_template_impl
    {
        static std::false_type test(...);

        template <typename...Us>
        static std::true_type test(Tmpl<Us...> const &);

        using result = decltype(test(std::declval<T>()));
    };

    template <typename T, template <class...> class Tmpl>
    using is_derived_from_template = typename is_derived_from_template_impl<T, Tmpl>::result;

    template <typename T, template <class...> class Tmpl>
    constexpr auto is_derived_from_template_v = is_derived_from_template<T, Tmpl>::value;


    // free function version of shared_from_this

    template<class T> 
    auto shared_from(enable_shared_from_this<T>* p) 
    -> std::shared_ptr<T>
    {
        return p->shared_from_this();
    }

    // specific shared_ptr construction from type T

    template<class T> 
    auto shared_from(T*p) 
    -> enable_if_t
    <
        is_derived_from_template_v
        <
            T, 
            enable_shared_from_this
        >, 
        std::shared_ptr<T>
    >
    {
        return std::shared_ptr<T>(p->shared_from_this(), p);
    }

}

// everything is an Object - yuk, but ok, if you wish...
struct Object : std::enable_shared_from_this<Object>
{
};

struct GameObject : Object
{

};

struct IRenderable
{
    virtual void render() {};
};

extern int emit(const char* str);

struct RederableGameObject : GameObject, IRenderable
{
    auto as_shared_renderable() -> std::shared_ptr<RederableGameObject>
    {
        return notstd::shared_from(this);
    }

    auto as_shared_renderable() const -> std::shared_ptr<const RederableGameObject>
    {
        return notstd::shared_from(this);
    }

    void e() const {
        emit("const");
    }
    void e()  {
        emit("mutable");
    }


};



int main()
{

    auto rgo = std::make_shared<RederableGameObject>();

    // prove it works
    auto p1 = rgo->as_shared_renderable();

    // prove it works with a const object also
    auto p2 = static_cast<const RederableGameObject&>(*rgo).as_shared_renderable();

    p1->e();
    p2->e();
}