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