1

I am trying to create a function that sets the root node of a LinkedList. However, when I run the following piece of code:

#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;
}

I get this error at the line root = &new_node;:

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

However, new_node does have all the expected arguments for the struct Node.

songyuanyao
  • 169,198
  • 16
  • 310
  • 405
Adam Lee
  • 436
  • 1
  • 14
  • 49
  • Note that with your code, you can only have one list by type... – Jarod42 May 06 '20 at 08:40
  • 1
    Was it you asking a question about template `main` before? May I suggest getting [a good book about templates](https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list)? Templates are an advanced topic and they can become a headache without solid foundations. – Yksisarvinen May 06 '20 at 08:46
  • 1
    Based on your use of `&`, I recommend that you first implement a linked list entirely without templates in order to learn the basics. – molbdnilo May 06 '20 at 08:52

1 Answers1

5

root is a variable template, you need to specify template argument when using it. e.g.

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

BTW: new_node is a local object which will be destroyed when get out of SetRoot. After that root<K> becomes dangled.

songyuanyao
  • 169,198
  • 16
  • 310
  • 405