Help with function template defined in header file

Hi could anyone help me with defining a function template in header file?
I tried to define the template function within a header file and its cpp,
and the error msg came out at linkning time. (using VC++)

Thanks a lot!!!.

Error msgs:
1
2
3
4
Linking...
Main.obj : error LNK2001: unresolved external symbol "double __cdecl max2(double,double)" (?max2@@YANNN@Z)
Debug/tool.exe : fatal error LNK1120: 1 unresolved externals
Error executing link.exe.


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
// tool.h
template <class T> T max2 ( T a, T b );

// tool.cpp
#include <iostream>
#include "tool.h"
template <class T> T max2 ( T a, T b )
{return (a>=b) ? a : b; }

// Main.cpp
#include <iostream>
#include "tool.h"
void main()
{
	double temp = max2(1.5, 2.5);
	cout << temp << endl;
}
Last edited on
Try moving the definition of max2 directly into "tool.h"
Both the declaration and definition of templates must be included. This is because template functions cannot be compiled and linked independently, since they are generated on request for the specific types they are instantiated with.
The declarations and definitions of the class template member functions should all be in the same header file.
1
2
3
4
// tool.h
#include <iostream>
template <class T> T max2 ( T a, T b )
{return (a>=b) ? a : b; }


// Main.cpp
#include <iostream>
#include "tool.h"
void main()
{
double temp = max2(1.5, 2.5);
cout << temp << endl;
}
martinlb and sushmat thanks for your reply and my tool finally works!

Still I am confused about what happens in compiling and linking time of function template. I originally expected that separating my codes from .h file will make it more clean and readable, cause some of my function templates contains large segments of codes...

Is there any website or material explaining this in detail so I can figure it out myself? Thanks again!!
Topic archived. No new replies allowed.