类模板的智能指针的矢量

vector of smart pointer of class template

本文关键字:指针 智能      更新时间:2023-10-16

我尝试使用std::share_ptr来替换传统Node类中的指针。

#include <iostream>
#include <vector>
#include <algorithm>
#include <memory>
template<class T>
class Node
{
public:
typedef std::shared_ptr< Node<T> > Ptr;
public:
T   data;
std::vector< Node<T>::Ptr > childs;
};
int main()
{
return 0 ;
}

但是,它指出std::vector的输入不是有效的模板类型参数。

所以问题是;如果我想使用模板类的智能指针作为STL容器的参数,如何使该类工作。

错误消息为(VS 2015(

Error   C2923   'std::vector': 'Node<T>::Ptr' is not a valid template type argument for parameter '_Ty' 
Error   C3203   'allocator': unspecialized class template can't be used as a template argument for template parameter '_Alloc', expected a real type    

[编辑]

添加head-include文件,并使其可运行。

添加错误消息

你的代码对我来说似乎是正确的,至少它在gccclang上都编译(但什么都不做(,没有办法尝试vs2015对不起,有可能不符合c++11?

无论如何,这里有一个稍微扩展的代码版本,它可以做一些事情(并展示了如何使用您试图掌握的shared_ptr(:

#include <iostream>
#include <vector>
#include <algorithm>
#include <memory>
#include <sstream>
template<class T>
class Node
{
public:
typedef std::shared_ptr< Node<T> > Ptr;
T data;
std::vector< Ptr > childs;
void add_child(T data) {
auto p = std::make_shared<Node<T>>();
p->data = data;
childs.push_back(p);
}
std::string dump(int level = 0) {
std::ostringstream os;
for (int i = 0; i < level; ++i) os << 't';
os << data << 'n';
for (auto &c: childs) os << c->dump(level + 1);
return os.str();
}
};
int main()
{
Node<int> test;
test.data = 1;
test.add_child(2);
test.add_child(3);
std::cout << test.dump();
return 0 ;
}