【问题标题】:C++ template class: No matching member function for call to 'push_back'C++ 模板类:没有匹配的成员函数调用“push_back”
【发布时间】:2020-09-11 21:46:52
【问题描述】:

我正在尝试构建一个模板类,该类包含一个指向向量的指针,该向量本身包含指针。

template <typename S, typename T>
struct MyClass
{
    std::shared_ptr<aNode<S,T>> head{nullptr};
    std::shared_ptr<std::vector<aNode<S,T>>> positionList; // <<- This guy

    void add(S const & k, T const & v)
    {
        std::shared_ptr<aNode<S,T>> newNode = std::make_shared<aNode<S,T>>();
        newNode->set_data(k, v);
        if (head == nullptr) {
            head = newNode;
        } else {
            auto current = head;
            while (current->next != nullptr) {
                current = current->next;
            }
            current->next = newNode;
        }
        positionList->push_back(newNode); // <<- Error here
    } 
    [...]

在第 20 行,编译器抛出错误 No matching member function for call to 'push_back'

现在 -> 运算符应该让我可以访问向量,并且向量当然有一个 push_back 方法。我唯一能想到的是向量没有初始化。 将第 4 行更改为 std::shared_ptr&lt;std::vector&lt;aNode&lt;S,T&gt;&gt;()&gt; positionList; 会引发错误

Member reference base type 'std::__1::shared_ptr<std::__1::vector<aNode<std::__1::basic_string<char>, std::__1::basic_string<char> >, std::__1::allocator<aNode<std::__1::basic_string<char>, std::__1::basic_string<char> > > > ()>::element_type' (aka 'std::__1::vector<aNode<std::__1::basic_string<char>, std::__1::basic_string<char> >, std::__1::allocator<aNode<std::__1::basic_string<char>, std::__1::basic_string<char> > > > ()') is not a structure or union

(仍在第 20 行)。

我哪里错了?

【问题讨论】:

  • 请在问题中包含minimal reproducible example
  • positionlist 是指向节点向量的共享指针,但您尝试将共享指针推回不适合的节点
  • newNode 的类型为 std::shared_ptr&lt;aNode&lt;S,T&gt;&gt;,但您的向量存储 aNode&lt;S,T&gt;
  • std::shared_ptr&lt;std::vector&lt;aNode&lt;S,T&gt;&gt;()&gt; 是错误的。要在 shared_ptr 中初始化空向量,只需在构造函数中使用 std::make_shared()
  • 你真的想要向量上的指针,你分享吗? std::vector 通常就足够了。

标签: c++ pointers templates shared


【解决方案1】:

根据你的描述,positionList应该是:

std::shared_ptr<std::vector<std::shared_ptr<aNode<S, T>>>> positionList;

【讨论】:

  • 呃!我看不到那里的树木 - 非常感谢 Jarod42!
猜你喜欢
  • 1970-01-01
  • 2020-08-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多