1

I get an linker error (2001, unresolved external symbol) with the following code. It only happens with templates, i can perfectly do the same thing with void, int, etc.

//a.h

template<typename T> T foo( DWORD );



//a.cpp

#include "a.h"

template<typename T> T foo( DWORD bar )
{
    return T();
}



//main.cpp

#include "a.h"

void something()
{
    int hello = foo<int>( 1 );
}

It does work when i put the declaration of foo inside the header file like this

//a.h

template<typename T> T foo( DWORD bar )
{
    return T();
}
user2361925
  • 81
  • 1
  • 8
  • 4
    You should read about [why can templates only be implemented in the header file][1] [1]: http://stackoverflow.com/questions/495021/why-can-templates-only-be-implemented-in-the-header-file – piotrekg2 Aug 28 '13 at 19:09

1 Answers1

0

The C++ compiler needs to see the template definition in order to perform implicit instantiation. This means, the C++ compiler can only generate the object code for the template function call automatically if it knows the implementation at the time you invoke it.

You can, however, rely on explicit instantiation instead. This means you ask the compiler to generate the C++ code for the specific instance of the template that you specify. Then, the C++ compiler during link time will be able to find this implementation (via external linkage) when the template is used in main.cpp.

//a.cpp

#include "a.h"

template<typename T> T foo( DWORD bar )
{
    return T();
}

template int foo<int> (DWORD); // explicit instantiation
jxh
  • 69,070
  • 8
  • 110
  • 193