Tuesday, April 17, 2007

Template Function in CPP file

Is it possible to do that ?? i mean writing template functions in c++ file ??? , Yeah it is possible.
Suppose we have class , its name is CSimple.


so the header may look like this
///CSimple.h
template <typename T>
class CSimple
{
     T anything;
public :
     void SimpleTest();
};
So we need to put the SimpleTest function outside the class. If it is the same header file , it is fairly easy to do
like this
template <typename T>
void CSimple<T> :: SimpleTest()
{
}
thats all. No pains. But it is in the c++ file you will get linker error (At least in VS ).
So to do that we can define .cpp file as this

 // CSimple.cpp
#include
"CSimple.h"
template <typename T>
void CSimple<T> :: SimpleTest()
{


}
template CSimple<int>;
so in your main if are creating a creating an object of template class like CSimple<int> it will compile perfectly.


If u are creating objects of other types you have to give that class information in the cpp file. Like if you want to instantiate the template class with float you need to give template CSimple<float> in the cpp files. So sometimes it may not be possible to modify cpp files. So it is better to create a new cpp files and include the original cpp in that , also we can define our template class in that too. Like shown below


 /// CComplex.cpp
#include "CSimple.cpp"
template  CSimple <float>


This will work definitely .

1 comment:

Sarath said...

Nice tweak KD.
I\'d like to add some more to this.When the compiler sees a template class, it will look up with same file or with the dependend files included in the compilation unit. Each time it sees it, it expands it\'s full definition and finally the linker knows how to avoid the duplicated definitions of the class.
For our purpose we can do like this. But when you are writing libraries it will be hard to adopt this method. Best examples are Visual C++ libraries and boost libraries. The complete source of Afx template class is available at afxtempl.h. Boost template classes are defined in hpp (.h & .cpp files combined).
Eda I could not differentiate between including .h implemented template class the other one which consist of .h & .cpp files :( both are same no? because the template class\'s header file not including anywhere other than it\'s CPP file. The template class\'s CPP file being included in those units using. For the sake of defining C++ file, yea sure this can be used. But practically it\'s rarely used.
Regards,
Sarath