I have a problem with linker. I am trying to create template Tree but since I'm having some problems with using templates (my first time) I decided to do a "test template program". I have been looking for anserws before posting and tried some solutions posted on the forum but none has worked for me. Here is the test program:
.h file
#pragma once
template <class T>
class Node {
public:
Node();
Node(T value);
~Node();
void manualTree();
private:
T data;
Node *left, *right, *parent;
};
.cpp file
#include "stdafx.h"
#include <iostream>
#include "Node.h"
using namespace std;
template<class T>
Node<T>::Node(T val) {
data = val;
}
template<class T>
void Node<T>::manualTree() {
Node* root = new Node(1);
root->left = new Node(2);
root->right = new Node(3);
cout << "left : " << root->left->data << endl;
cout << "right : " << root->right->data << endl;
cout << "root : " << root->data << endl;
}
template class Node<int>;
main body
#include "stdafx.h"
#include "arithmetics.h"
#include <iostream>
#include "Node.h"
using namespace std;
int main()
{
Node<int> n;
n.manualTree();
return 0;
}
Here is what i get after trying to call manualTree() function: Severity Code Description Project File Line Column Suppression State
Error LNK1120 2 unresolved externals zad6 - szablony C:\Users\Piotr\source\repos\zad6 - szablony\Debug\zad6 - szablony.exe 1 1
Error LNK2019 unresolved external symbol "public: __thiscall Node<int>::~Node<int>(void)" (??1?$Node@H@@QAE@XZ) referenced in function _main zad6 - szablony C:\Users\Piotr\source\repos\zad6 - szablony\zad6 - szablony\main.obj 1 1
Error LNK2019 unresolved external symbol "public: __thiscall Node<int>::Node<int>(void)" (??0?$Node@H@@QAE@XZ) referenced in function _main zad6 - szablony C:\Users\Piotr\source\repos\zad6 - szablony\zad6 - szablony\main.obj 1 1
EDIT:
I have moved everything to the .h file, like they said in the linked post and i still get the same warnings sometimes with a few more. Already tried putting into .cpp file these lines and still not working (with the same warnings):
template class Node<int>;
or
Node<int> n;
new .h file
#pragma once
template <class T>
class Node {
public:
Node();
Node(T value) {
data = value;
}
~Node();
void manualTree() {
Node* root = new Node(1);
root->left = new Node(2);
root->right = new Node(3);
cout << "left : " << root->left->data << endl;
cout << "right : " << root->right->data << endl;
cout << "root : " << root->data << endl;
}
private:
T data;
Node *left, *right, *parent;
};