Correctly implent large template class

Jul 31, 2012 at 12:35pm
I have a large class, which can be used with multiple data structures. So - I made it a template class, but was struck with linking problems. Now I don't know which would be the best road to take to resolve these linking problems.

So a simple example:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
//a.h
template<class T> class A
{
 T a;
 void print();
 T ret();
} 
//a.cpp
template<class T>void A<T>::print(){cout << a;}
template<class T>T A<T>::ret(){ return a;}


template void A<int>::print(){cout << a;}
template int A<int>::ret(){ return a;}

And the question:
Is it possible to implent a large class in a separate cpp file without
1
2
template void A<int>::print(){cout << a;}
template int A<int>::ret(){ return a;}

for each data type?
Jul 31, 2012 at 12:38pm
No. You have to implement it in the header.
Jul 31, 2012 at 1:00pm
Damn :( Looks like then it's simpler to use inheritance.
Jul 31, 2012 at 1:09pm
Is it really a problem implementing the template in the header? Templates is a bit special so you can put the function implementations outside the class definition if you like. If you just want to have them in different files you could create a file that you include in the header file.
1
2
3
4
5
6
7
8
9
10
11
12
//a.h
template<class T> class A
{
 T a;
 void print();
 T ret();
} 
#include "a.impl"

//a.impl
template<class T>void A<T>::print(){cout << a;}
template<class T>T A<T>::ret(){ return a;}
Jul 31, 2012 at 2:40pm
I believe you could also use explicit instantiation, if you know exactly what types the class template with be used with, but the inclusion model does not have that limitation.
Topic archived. No new replies allowed.