c++ - C++模板错误: ‘=’ token 之前缺少模板参数

标签 c++ templates struct

我正在尝试创建一个设置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 = &new_node;行收到此错误:

error: missing template arguments before ‘=’ token root = &new_node;



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

最佳答案

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

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

顺便说一句:new_node是一个本地对象,当离开SetRoot时将被销毁。之后,root<K>挂了起来。

关于c++ - C++模板错误: ‘=’ token 之前缺少模板参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61630821/

相关文章:

c - 尝试使用 malloc 时出现段错误

c - 将 uint64_t 数据类型存储在 C union 中存在的 char 类型字段中

c - 错误 : invalid type argument of unary '*' (have 'int' )

c# - 用模板覆盖基类的抽象类

c++ - 在多态指针 vector 中搜索特定类型及其子类型

c++ - 在 C++ 中没有 **std::fixed** 的 **std::setprecision()** 的作用是什么?

c++ - 回调函数语法

C++模板,使用std迭代器的错误

C++ 图像比较每个 block 的平均位数

c++ - 在 if 语句中调用重载的构造函数失败