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 .