【发布时间】:2018-07-31 08:22:02
【问题描述】:
我尝试使用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
[编辑]
添加头包含文件,并使其可运行。
添加错误信息
【问题讨论】:
-
不应该是
std::vector<Ptr> childs;吗?似乎可以使用正确的包括:ideone.com/IzFJ75 -
您需要
#include <memory>和#include <vector>。如果这不能解决您的问题,请更新问题以显示产生错误的确切代码,最好还显示确切的错误消息。 -
请逐字提供minimal reproducible example 和错误信息
-
@mch 在该范围内,
Ptr和Node<T>::Ptr之间没有区别 -
一句警告(可能针对您的未来,下一个问题)。想象一下,你有一棵巨大的树,上面有(固定的)代码……现在是销毁时间。然后根节点的析构函数调用
childsvedtor 的析构函数,后者又调用子节点析构函数等等,直到...取决于树的深度...堆栈溢出!耶 - 为了纪念这个网站的名字。我用列表而不是树(指向链接列表节点的共享指针)做了类似的事情,并看到了堆栈溢出。
标签: c++ templates stl smart-pointers