微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

将 std::shared_ptr<Derived<T>> 转换为 std::shared_ptr<Base>

如何解决将 std::shared_ptr<Derived<T>> 转换为 std::shared_ptr<Base>

我有一个基类和一个模板化的派生类,如下

class ComponentArray_Base
{
 public:
     virtual ~ComponentArray_Base() = default;              
     virtual void EntityDestroyed(Entity entity) = 0;       
};


template <typename cType>
class ComponentArray : public ComponentArray_Base
{
 //Derived class implementation...
}

然后在代码中,在两个类之外,我尝试将派生类添加到无序映射中

mComponentArrays.insert({ TypeName,std::make_shared<ComponentArray<cType>> });

这给了我错误

C:\Users\davis\source\repos\ECS\ECS\Component.h(91,1): error C2664: 'void std::_Hash<std::_Umap_traits<_Kty,_Ty,std::_Uhash_compare<_Kty,_Hasher,_Keyeq>,_Alloc,false>>::insert(std::initializer_list<std::pair<const char *const,std::shared_ptr<ComponentArray_Base>>>)': cannot convert argument 1 from 'initializer list' to 'std::initializer_list<_Ty>'
1>        with
1>        [
1>            _Kty=const char *,1>            _Ty=std::shared_ptr<ComponentArray_Base>,1>            _Hasher=std::hash<const char *>,1>            _Keyeq=std::equal_to<const char *>,1>            _Alloc=std::allocator<std::pair<const char *const,std::shared_ptr<ComponentArray_Base>>>
1>        ]
1>        and
1>        [
1>            _Ty=std::pair<const char *const,std::shared_ptr<ComponentArray_Base>>
1>        ]

在使用原始指针时我似乎没有遇到这个问题,并且无法弄清楚问题是什么,因为应该为 const char* 定义散列函数

如下使用 std::static_ptr_cast 也会报错,

mComponentArrays.insert({ TypeName,std::static_pointer_cast<ComponentArray_Base>(std::make_shared<ComponentArray<cType>>) });

给我

 'std::static_pointer_cast': none of the 2 overloads Could convert all the argument types
1>C:\Program Files (x86)\Microsoft Visual Studio\2019\Community\VC\Tools\MSVC\14.28.29910\include\memory(2095,29): message : Could be 'std::shared_ptr<ComponentArray_Base> std::static_pointer_cast<ComponentArray_Base,ComponentArray<cType>>(std::shared_ptr<ComponentArray<cType>> &&) noexcept'
1>        with
1>        [
1>            cType=Renderable
1>        ]

解决方法

我成功编译了下面的例子。我错过了什么吗?

#include <unordered_map>
#include <string>
#include <memory>

class ComponentArray_Base
{
 public:
     virtual ~ComponentArray_Base() = default;              
     virtual void EntityDestroyed(int entity) = 0;       
};


template <typename cType>
class ComponentArray : public ComponentArray_Base
{
    void EntityDestroyed(int entity) override
    {
        return;
    }
 //Derived class implementation...
};

std::unordered_map<std::string,std::shared_ptr<ComponentArray_Base>> mComponentArrays;

int main()
{
    mComponentArrays.insert({ "Sth",std::make_shared<ComponentArray<int>>() });

    return 0;
}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。