0

I have a class Node with a template
this is header file

// node.h
#ifndef NODE_H
#define NODE_H
#include <iostream>

using namespace std;

template <typename T>
class Node
{
private:
    T content;
    Node<T> *next;
public:
    Node();
    Node(T);

    template <typename Y>
    friend ostream &operator <<(ostream &, const Node<Y> &);
};
#endif // NODE_H

and that's the implementation

// node.cpp
#include "node.h"

using namespace std;

template<typename T>
Node<T>::Node()
{
    content = 0;
    next = NULL;
}

template<typename T>
Node<T>::Node(T c)
{
    content = c;
    next = NULL;
}

template<typename Y>
ostream &operator<<(ostream &out, const Node<Y> &node)
{
    out << node.content;
    return out;
}

and here is the main file

// main.cpp
#include <iostream>
#include "node.cpp"

using namespace std;

int main()
{
    Node<int> n1(5);

    cout << n1;

    return 0;
}

this way, it works perfectly, but i don't think it's good to include cpp file.
so i included node.h but i get this errors

pathtofile/main.cpp:8: error: undefined reference to `Node<int>::Node(int)'
pathtofile/main.cpp:10: error: undefined reference to `std::ostream& operator<< <int>(std::ostream&, Node<int> const&)'

I really want to follow best practices, and i always separate code declaration from implementation; but this my first time working with templates.

bondif
  • 308
  • 1
  • 5
  • 18
  • 4
    Common practice is to place the template class and methods in one header file. – Thomas Matthews May 22 '18 at 13:49
  • 1
    It's not a "best practice" but rather a language restriction that the entire definition of a template class be declared inside of the header, otherwise compilation will fail. It is however bad practice to include a .cpp file. While the compiler will allow it because `#include` will read any file, the `.cpp` file extension has a specific implicit purpose of being a single compileable translation unit. – flamewave000 May 22 '18 at 14:08
  • 1
    You should take a look at this https://stackoverflow.com/questions/495021/why-can-templates-only-be-implemented-in-the-header-file - doesn't answer your question directly but might give you some insights. – Ronen Ness May 22 '18 at 14:58

0 Answers0