views:

59

answers:

2

I'm trying to overload a "display" method as follows:

template <typename T> void imShow(T* img, int ImgW, int ImgH);
template <typename T1, typename T2> void imShow(T1* img1, T2* img2, int ImgW, int ImgH);

I am then calling the template with unsigned char* im1 and char* im2:

imShow(im1, im2, ImgW, ImgH);

This compiles fine, but i get a link error "unresolved external symbol" for:

imShow<unsigned char,char>(unsigned char *,char *,int,int)

I don't understand what I did wrong!

+1  A: 

You need to define that template in the header file if your compiler doesn't have the "export" template feature (only compilers based on the EDG frontend have, which GCC and MSVC do not). You can alternatively explicitly instantiate the function template in the .cpp file (if you placed its definition there):

template void imShow(unsigned char* img1, char* img2, int ImgW, int ImgH);

But as soon as you pass another pair of types you haven't explicitly instantiated like that, it again fails to link. So you need to put the function template's definition into the header, so the compiler sees it when calling the function, and instantiates a copy of the function itself.

Johannes Schaub - litb
I defined the template (without instantiating it) in the .cpp file and it is working.. I'm using Visual Studio 2008, does it mean it has the "export" template feature?
matt
@matt with ".cpp" file i meant you compile your template separate from the code using it. If you do `#include "file.cpp"` in the translation unit using it, that's different. If you compile separately, you will earn linker errors.
Johannes Schaub - litb
Oh ok it makes perfect sense now! The .cpp file where the function is defined is the only place where I need it, but I'll be aware of this if I need it anywhere else! Thanks
matt
A: 

You probably forgot to define your template function properly. Where are the definitions? I don't see any in your post.

AndreyT
I needed to define the method *properly* ! I defined it as imShow instead of MyClass::imShow... thank you! Sorry, beginner mistake...
matt