I am learning template programming and have come across an error i cannot understand. My task involves 3 files 1) A main File (with main function)
#include<iostream>
#include "templates.h"
int main(){
trial <int>x;
x.input(3);
std::cout<<x.ret();
return 0;
}
2) A header File
#ifndef templ
#define templ
template<typename T>
class trial{
T val;
public:
void input(T x);
T ret();
};
#include "templateref.cpp"
#endif
3) A .cpp file used define the functions of class trial
#ifndef templ
#define templ
#include"templates.h"
#endif
template<class T>
void trial<T>::input(T x){
val = x;
return ;
}
template<class T>
T trial<T>::ret(){
return val;
}
As i undestand from here "Undefined reference to" template class constructor and https://www.codeproject.com/Articles/48575/How-to-define-a-template-class-in-a-h-file-and-imp i had to instantiate the template class for it to work.
My problem occurs when I try to compile it. when I do
clang++ templates.cpp templateref.cpp -Wall -o template
I get the error
templateref.cpp:14:6: error: variable has incomplete type 'void'
void trial<T>::input(T x){
^
templateref.cpp:14:11: error: expected ';' at end of declaration
void trial<T>::input(T x){
^
;
templateref.cpp:14:11: error: expected unqualified-id
templateref.cpp:20:11: error: qualified name refers into a specialization of variable template 'trial'
T trial<T>::ret(){
~~~~~~~~^
templateref.cpp:14:6: note: variable template 'trial' declared here
void trial<T>::input(T x){
^
4 errors generated.
This is fixed by
clang++ templates.cpp -Wall -o template
the compilation runs without errors and gives results as expected .
So my question is (sorry for the long explanation , as i couldnt explain my question in shorter words) why cant I link these files together and what am i missing?