【问题标题】:vector of smart pointer of class template类模板的智能指针向量
【发布时间】: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&lt;Ptr&gt; childs;吗?似乎可以使用正确的包括:ideone.com/IzFJ75
  • 您需要#include &lt;memory&gt;#include &lt;vector&gt;。如果这不能解决您的问题,请更新问题以显示产生错误的确切代码,最好还显示确切的错误消息。
  • 请逐字提供minimal reproducible example 和错误信息
  • @mch 在该范围内,PtrNode&lt;T&gt;::Ptr 之间没有区别
  • 一句警告(可能针对您的未来,下一个问题)。想象一下,你有一棵巨大的树,上面有(固定的)代码……现在是销毁时间。然后根节点的析构函数调用childs vedtor 的析构函数,后者又调用子节点析构函数等等,直到...取决于树的深度...堆栈溢出!耶 - 为了纪念这个网站的名字。我用列表而不是树(指向链接列表节点的共享指针)做了类似的事情,并看到了堆栈溢出。

标签: c++ templates stl smart-pointers


【解决方案1】:

您的代码对我来说似乎是正确的,至少它在 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 ;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-08-20
    • 2021-09-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-01-24
    • 2017-10-16
    相关资源
    最近更新 更多