删除指针表单模板

remove pointer form template

提问人:NiHoT 提问时间:11/18/2022 最后编辑:rturradoNiHoT 更新时间:11/19/2022 访问量:138

问:

我正在尝试编写一个简单的列表来管理智能指针。添加指向列表的指针,当列表被销毁时,所有指向的对象都会被销毁。这是一个有效的代码:

#include <iostream>
#include <list>

class Obj
{
public:
   Obj(){std::cout<<"created "<<this<<" \n";}
   ~Obj(){std::cout<<"deleted "<<this<<" \n";}
};

template <class T>
class TList : public std::list<std::shared_ptr<T>>
{
public:
   TList(){}
   ~TList(){
   }
   TList &operator<<(T* t)
   {
      std::shared_ptr<T> p;
      p.reset(t);
      this->push_back(p);
      return *this;
   }
};


int main(int argc, char *argv[])
{
   TList<Obj> list;
   list<<new Obj;
   return 0;
}

但是我想使用 T 的指针来声明这样的列表:

 TList<Obj*> list;

这是我尝试过但不起作用的代码,模板错误总是模糊不清:

#include <iostream>
#include <list>

class Obj
{
public:
   Obj(){std::cout<<"created "<<this<<" \n";}
   ~Obj(){std::cout<<"deleted "<<this<<" \n";}
};

template <class T>
class TList : public std::list<std::shared_ptr<std::remove_pointer<T>::type>>
{
public:
   TList(){}
   ~TList(){
   }
   TList &operator<<(T t)
   {
      std::shared_ptr<std::remove_pointer<T>::type> p;
      p.reset(t);
      this->push_back(p);
      return *this;
   }
};

int main(int argc, char *argv[])
{
   TList<Obj*> list;
   list<<new Obj;
   return 0;
}

错误:

main.cpp(12): warning C4346: 'std::remove_pointer<_Ty>::type': dependent name is not a type
main.cpp(12): note: prefix with 'typename' to indicate a type
main.cpp(25): note: see reference to class template instantiation 'TList<T>' being compiled
main.cpp(12): error C2923: 'std::shared_ptr': 'std::remove_pointer<_Ty>::type' is not a valid template type argument for parameter '_Ty'
main.cpp(12): note: see declaration of 'std::remove_pointer<_Ty>::type'
main.cpp(12): error C3203: 'shared_ptr': unspecialized class template can't be used as a template argument for template parameter '_Ty', expected a real type
C++ 模板 std 智能指针

评论

1赞 Patrick Roberts 11/18/2022
这回答了你的问题吗?我必须在哪里以及为什么必须放置“template”和“typename”关键字?
3赞 Some programmer dude 11/18/2022
请注意,标准容器并不是真正为公共继承而设计的。您应该考虑将重载运算符函数创建为非成员函数(类似或类似函数)<<template<typename T> std::list<std::shared_ptr<T>>& operator<<(std::list<std::shared_ptr<T>>&, T&&);
1赞 Serge Ballesta 11/19/2022
或者,您可以使用组合模式,即将成员封装在类中,并将大多数操作委派给它。std::list
1赞 rturrado 11/19/2022
如前所述,我会考虑使用聚合而不是继承。此外,在使用智能指针时,更喜欢使用而不是使用智能指针。演示TListstd::make_sharednew
1赞 QuentinUK 11/19/2022
而不是把std::remove_pointer<T>::typestd::remove_pointer_t<T>

答: 暂无答案