我尝试使用 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
[编辑器]
添加头包含文件,并使它们可运行。
添加错误信息
最佳答案
你的代码对我来说似乎是正确的,至少它在 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 ;
}
关于c++ - 类模板的智能指针 vector ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51608691/