Adam Lee
Adam Lee

Reputation: 586

C++ Template Error: missing template arguments before ‘=’ token

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.

Upvotes: 1

Views: 5181

Answers (1)

songyuanyao
songyuanyao

Reputation: 173044

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.

Upvotes: 5

Related Questions