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

时间:2021-07-02 20:48:18

标签: c++ c++11 visual-studio-2019

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

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>        ]

1 个答案:

答案 0 :(得分:0)

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

#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;
}
相关问题