简体   繁体   中英

vector of smart pointer of class template

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

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 ;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM