How to write a template using header and implementation

I have the .h and cpp files for my class and :
1
2
template <class TT_1>
void write(TT_1 value);


Where I have to write "template <class TT_1>" at header file or into the cpp file? (I have compiler problems and my IDE seams to be confused...).
By now I'm writing the whole function all at h.file but I'd like to write it at cpp file.
Any idea ? Thanks
templates have to be completely specified in the header file (implementation and all).
Well, you can have the definition and implementation in two separate files.

File myTemplate.h:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
//myTemplate.h
#ifndef _MY_TEMPLATE_H
#define _MY_TEMPLATE_H

template <class T>
class myTemplate
{
private:
   T m_t;

public:
   myTemplate(T t)
   {
      m_t = t;
   }

   T get();
};

#include "myTemplate.tlt"

#endif 


File myTemplate.tlt (or whatever extension you want to be associated with the implementation of a template. Making it a .h file would be confusing):
1
2
3
4
5
6
//myTemplate.tlt
template <class T>
T myTemplate<T>::get()
{
   return m_t;
}


File main.cpp:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
//main.cpp
#include <iostream>
using namespace std;

#include "myTemplate.h"

int main()
{
   myTemplate<int> templateInstance1(5);
   myTemplate<float> templateInstance2(1.0);

   cout<<templateInstance1.get()<<endl;
   cout<<templateInstance2.get()<<endl;

   return 0;
}


You could have your IDE apply syntax highlighting to your template implementation file. It's not recommended to do this but it's possible.
Last edited on
Topic archived. No new replies allowed.