类模板的智能指针的矢量
vector of smart pointer of class template
我尝试使用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文件,并使其可运行。
添加错误消息
你的代码对我来说似乎是正确的,至少它在gcc和clang上都编译(但什么都不做(,没有办法尝试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 ;
}
相关文章:
- 1d 智能指针不适用于语法 (*)++
- 优先顺序:智能指针和类析构函数
- 对于C++中使用智能指针的指针算术限制,有没有一种变通方法
- 智能指针作为无序映射键,并通过引用进行比较
- 智能指针概念所有权和寿命
- 正在理解智能指针,但出现错误:未分配正在释放的指针
- 尝试使用智能指针时引发异常
- 我可以制作指向智能指针的智能指针吗?
- 通过智能指针和转换对基本模板参数进行模板推导
- OpenCV 我应该使用智能指针来防止内存泄漏吗?
- 从堆栈分配的原始指针构造智能指针
- 初始化指向类实例的智能指针并访问其方法
- 如何使用 std::make_shared 创建基类类型的智能指针?
- 给定一个指向堆分配内存的指针,智能指针实现如何为其找到合适的释放函数?
- 编译器不会使用 -std=c++11 编译智能指针
- 具有智能指针的多态性
- C++:矢量分配器行为、内存分配和智能指针
- 通过简单的包装指针C++智能指针性能和差异
- 矢量中的自动指针(智能)
- Std::vector的对象/指针/智能指针传递对象(总线错误:10)