提问人:NiHoT 提问时间:11/18/2022 最后编辑:rturradoNiHoT 更新时间:11/19/2022 访问量:138
删除指针表单模板
remove pointer form template
问:
我正在尝试编写一个简单的列表来管理智能指针。添加指向列表的指针,当列表被销毁时,所有指向的对象都会被销毁。这是一个有效的代码:
#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
答: 暂无答案
评论
<<
template<typename T> std::list<std::shared_ptr<T>>& operator<<(std::list<std::shared_ptr<T>>&, T&&);
std::list
TList
std::make_shared
new
std::remove_pointer<T>::type
std::remove_pointer_t<T>