簡體   English   中英

類模板的智能指針向量

[英]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包含文件,並使它們可運行。

添加錯誤消息

您的代碼對我來說似乎是正確的,至少它可以同時在gccclang上編譯(但什么也不做),沒有辦法嘗試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 ;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM