Reputation: 53
I try to use a std::share_ptr
to replace the pointer inside a traditional Node
class.
#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 ;
}
However, it states that the input of std::vector
is not a valid template type argument.
So the question is; How to make the class work, if I want to use a smart pointer of template class as the argument of STL container.
The error messages are (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
[Editor]
Add head include files, and make them run-able.
Add error message
Upvotes: 0
Views: 745
Reputation: 1422
Your code seems correct to me, at least it compiles (but does nothing) both on gcc and clang, no way to try vs2015 sorry, there is a chance that is not c++11 compliant?
Anyway here is a slightly expanded version of your code that do something (and shows how to use that shared_ptr you are trying to master):
#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 ;
}
Upvotes: 2