/* saved as mypair.cpp */
#include "mypair.h"
template <class T>
T mypair<T>::getmax ()
{
T retval;
retval = a>b? a : b;
return retval;
}
1 2 3 4 5 6 7 8 9
/* saved as mypair.h */
template <class T>
class mypair {
T a, b;
public:
mypair (T first, T second)
{a=first; b=second;}
T getmax ();
};
1 2 3 4 5 6 7 8 9 10
/* saved as sample.cpp */
#include <iostream>
usingnamespace std;
#include "mypair.h"
int main () {
mypair <int> myobject (100, 75);
cout << myobject.getmax();
return 0;
}
why does this error occur when i try to build this?
error LNK2019: unresolved external symbol "public: int __thiscall mypair<int>::getmax(void)" (?getmax@?$mypair@H@@QAEHXZ) referenced in function _main Sample.obj Sample
aw.. is that it? because i am used in putting all the definitions of my class in a .cpp file and the prototypes in a .h file.. but anyways, is there any possible way to define a template in .cpp file?
Nope. Think about it. If it's in a cpp file, you have to compile it. And how can the compiler do that when it doesn't know which types the template will be used with?
The entire template class, definition and implementation must be visible in code to the compiler when it compiles code using the template class.
You can, of course, put your implementations into a separate .inl file or something, and then include that at the bottom of the template header file: