Possible Duplicate:
Why can templates only be implemented in the header file?
I wrote a template function and the call of type int in function main:
template <class T> T max (T a, T b) { }
int main() {
max(1,2);
}
As most of the C++ books said, the int max(int,int) function will be generated during the compile time when the compiler meet the max(1,2).
But in another file, I wrote the declaration of the int max(int,int) and call it, but the compiler(actually the linker) caught an error said the reference of max(int,int) is not found.
extern int max(int,int);
max(1,2); // Error:undefined reference to max(int,int)
So , what’s the wrong point, and how can I call the max(int,int) function using extern and not a header file declaration.
Many thanks.
This question is only answered a few thousand times. The short form is: You either have to arrange for the template definition to be visible when used such that the compiler can implicitly instantiated the function template or you have to explicitly instantiate the function template.
Note, that the declaration
extern int max(int, int);declares a non-template functionmax()taking twointas parameter. This reference will never be satisfied by a function template, whether it is instantiated or not.