Ada*_*Lee 1 c++ templates struct
我正在尝试创建一个设置 LinkedList 根节点的函数。但是,当我运行以下代码时:
\n\n#include <iostream>\nusing namespace std;\n\ntemplate <typename K>\nstruct Node {\n Node<K>* next;\n const K value;\n};\n\ntemplate <typename K>\nNode<K>* root = NULL;\n\ntemplate <typename K>\nvoid SetRoot(const K &key) {\n Node<K> new_node = Node<K> {NULL, key};\n root = &new_node;\n}\n\nint main(int argc, char *argv[])\n{\n Node<int> n1 = Node<int> {NULL, 48};\n SetRoot(n1);\n\n return 0;\n}\nRun Code Online (Sandbox Code Playgroud)\n\n我在该行收到此错误root = &new_node;:
\n\n\n错误: \xe2\x80\x98=\xe2\x80\x99 令牌根 = &new_node; 之前缺少模板参数;
\n
但是,new_node确实具有 struct 的所有预期参数Node。
root是一个变量模板,使用时需要指定模板参数。例如
root<K> = &new_node;
// ^^^ specifying K which is the template parameter of SetRoot
Run Code Online (Sandbox Code Playgroud)
BTW:new_node是一个本地对象,退出时将被销毁SetRoot。之后root<K>就变得悬空了。