0

I have the following files

// File : Node.hpp

#ifndef NODE_H
#define NODE_H

template <class T>
class Node
{
public:
        Node(T data);     

private:
        T data_;
};

template class Node<int>;    
#endif

The second file is the Node.cpp

#include "Node.hpp"

template <class T>
Node<T>::Node(T data)
{
        data_ = data;
        next_ = 0;
}

Now in the a.cpp file I have

#include "Node.hpp"

#include <iostream>

int main()
{
     Node<int> a(20);
}

On compiling I get

meow@vikkyhacks ~/Arena/c/LinkedList $ g++ -I ./include/ lib/Node.cpp a.cpp -o main && ./main && echo && rm main
/tmp/ccswcJfR.o: In function `main':
a.cpp:(.text+0x15): undefined reference to `Node<int>::Node(int)'
collect2: ld returned 1 exit status

As you can see I have already template class Node<int>; to the Node.hpp, but still the linker is complaining about something which I believe is that it cannot find Node's constructor. How do I go about this ?

Duplicate Thread

This is not a duplicate of Why can templates only be implemented in the header file? because I already read that and its not helping me solve this problem. I need to know "How I can have the template constructor along with the class definition ?" and this is not discussed in the duplicate thread

Community
  • 1
  • 1
vikkyhacks
  • 3,190
  • 9
  • 32
  • 47
  • Regarding whether it's a duplicate or not: With templates, you have two options: put *all* template code in the header file, or explicitly instantiate all relevant templates. Both of these are covered by the answer to the duplicate question. – Angew is no longer proud of SO Jun 24 '14 at 15:27

1 Answers1

2

You need to explicitly instantiate the class in Node.cpp where the implementation is available and after the constructor definition. I.e. the template class Node<int>; line you have, move it into the Node.cpp file and after the constructor definition.

JarkkoL
  • 1,898
  • 11
  • 17