-2

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?

Niteya Shah
  • 1,809
  • 1
  • 17
  • 30
  • You need to put the templated functions in the header too. – Ted Lyngmo Dec 06 '18 at 07:36
  • They are member functions of the class which is defined in the header , so I can now only provide the definations of said function – Niteya Shah Dec 06 '18 at 07:39
  • Yes, and since the `` is actually part of the function signature, it can't be compiled before the user of the template supplies the type - so, put them in the header file. – Ted Lyngmo Dec 06 '18 at 07:41

1 Answers1

1

You shouldn't compile the member definition file – it's already included in the header.

Due to the include guard in that file, the entire header is excluded when the compiler processes it, and the class template definition doesn't exist.

Just compile the main file.

molbdnilo
  • 64,751
  • 3
  • 43
  • 82