【问题标题】:C++ Template Error: missing template arguments before ‘=’ tokenC++ 模板错误:在“=”标记之前缺少模板参数
【发布时间】:2020-05-06 08:36:28
【问题描述】:

我正在尝试创建一个设置 LinkedList 根节点的函数。但是,当我运行以下代码时:

#include <iostream>
using namespace std;

template <typename K>
struct Node {
  Node<K>* next;
  const K value;
};

template <typename K>
Node<K>* root = NULL;

template <typename K>
void SetRoot(const K &key) {
    Node<K> new_node = Node<K> {NULL, key};
    root = &new_node;
}

int main(int argc, char *argv[])
{
     Node<int> n1 = Node<int> {NULL, 48};
     SetRoot(n1);

    return 0;
}

我在root = &amp;new_node; 行收到此错误:

错误:在“=”标记根 = &new_node; 之前缺少模板参数

但是,new_node 确实具有结构 Node 的所有预期参数。

【问题讨论】:

  • 请注意,使用您的代码,您只能按类型拥有一个列表...
  • 您之前是不是问过关于模板main 的问题?我可以建议获得a good book about templates 吗?模板是一个高级主题,如果没有扎实的基础,它们可能会让人头疼。
  • 基于您对&amp;的使用,我建议您首先实现一个完全没有模板的链表,以便学习基础知识。

标签: c++ templates struct


【解决方案1】:

rootvariable template,使用时需要指定模板参数。例如

root<K> = &new_node;
//  ^^^   specifying K which is the template parameter of SetRoot

顺便说一句:new_node 是一个本地对象,当离开SetRoot 时将被销毁。之后root&lt;K&gt; 变成了悬空。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-10-11
    • 1970-01-01
    • 1970-01-01
    • 2015-09-12
    • 1970-01-01
    • 1970-01-01
    • 2016-09-18
    相关资源
    最近更新 更多