c++ - 类模板的智能指针 vector

标签 c++ templates stl smart-pointers

我尝试使用 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    

[编辑器]

添加头包含文件,并使它们可运行。

添加错误信息

最佳答案

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

关于c++ - 类模板的智能指针 vector ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51608691/

相关文章:

c++ - 在 C++ 中,static_cast<double>(a) 和 double(a) 有什么区别?

c++ - 转发与不转发传递给包装器的函数

c++ - 是否有用于 C(C99 或其他)的标准化和常用库,因为 STL 用于 C++?

c++ - 尝试使用取消引用的迭代器进行连接时,无法在字符串 vector 中连接字符串

c++ - CMake,GLFW3 OSX 链接错误

c++ - 使用 C++ Socket API 通过套接字连接将 HTML 标记发送到浏览器

c++ - 用于查找 f(Xi) 的最小值的索引的标准或 boost 算法

C++ 专用模板函数接收文字字符串

c++ - 从类模板中排除类型

c++ - 将 vector <unsigned char> 包装在流中?