Friday 16 August 2019

c++ - best practices: include .cpp file in main instead of .h file when using templates?

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


// node.h
#ifndef NODE_H
#define NODE_H
#include
using namespace std;
template
class Node
{
private:
T content;
Node *next;
public:
Node();
Node(T);
template
friend ostream &operator <<(ostream &, const Node &);
};
#endif // NODE_H

and that's the implementation


// node.cpp
#include "node.h"
using namespace std;
template
Node::Node()
{
content = 0;
next = NULL;
}
template
Node::Node(T c)
{
content = c;
next = NULL;
}
template
ostream &operator<<(ostream &out, const Node &node)
{
out << node.content;
return out;
}

and here is the main file


// main.cpp
#include
#include "node.cpp"
using namespace std;
int main()
{
Node 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::Node(int)'
pathtofile/main.cpp:10: error: undefined reference to `std::ostream& operator<< (std::ostream&, Node const&)'

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

No comments:

Post a Comment

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print &q...