Under normal circumstances, C + + templates are not allowed in header file declarations, implemented in CPP files. That's because when the CPP file is compiled, the memory has to allocate storage space for it. But the template itself is generic, and the compiler cannot know its size until the claim type is explicitly defined. So there will be a link failure.
// print.h #ifndef _print_ #define _print_templatevoid PRINT (T obj); #endif
// print.cpp #include " print.h " <iostream>using std;template <typename t> void print (T obj) {cout <<obj;}
// main.cpp#include"print.h"int main () { print (100 ); while (1); return 0 ;}
If you do this, you will be prompted:
1>link:e:\mycode\ template \debug\ template detach. exe not found or not built by the last incremental LINK; performing full Link1"void __cdecl print<int> (int)" in function _main 11 unresolved externals
Common Solutions A total of 2 kinds:
1 is the definition also in the header file, this is needless to say. Since there is no need to define the compiler in the CPP file, it is not necessary to initially allocate memory, and there will be no error.
2 with an explicit instantiation declaration, as I said earlier, the template function defined in the CPP file cannot allocate memory because there is no deterministic type. At this time, just give a definite type, that is, an explicit instantiation of the declaration, just need to be in the header file with a certain type of declaration again.
// print.h #ifndef _print_ #define _print_templatevoidvoid print<int> (int ); #endif
This will pass through the compilation.
C + + template separation