模板类型依赖和继承

template type dependecy and inheritance

本文关键字:继承 依赖 类型      更新时间:2023-10-16

我的模板方法定义为

template<class T>
const std::list<T>& GetList()
{
  return GetList(std::shared_ptr<Parent>(new T()));
}
const std::list<std::shared_ptr<Parent>>& GetList(const std::shared_ptr<Parent>&a)
{
    //
}

鉴于T是将父母作为父班的类的类型,例如

class Child1:public Parent
{};

编译错误: Can not convert const std::list<std::shared_ptr<Parent>>& to const std::list<T>&

有什么方法可以解决此问题,而无需将T的类型更改为共享_ptr?

定义必须匹配。

typedef std::shared_ptr<Parent> ParentPtr;
std::list<ParentPtr> GetParentList(const ParentPtr& a)
{
    //
}
template<class Child>
std::list<ParentPtr> GetParentListT()
{
    ParentPtr parent_ptr(new Child);
    return GetList(parent_ptr);
}
...
std::list<ParentPtr> my_list = GetParentListT<Child1>();

还确保在使用此代码之前定义了Child1(不仅是声明),否则编译器不会知道它是Parent的子类。