0

I tried the recommendation here. I have the following class with a templated member function defined in the implementation as follows:

Header (with compiler DLL import directive evaluated as __declspec(dllimport) in client application):

class __declspec(dllimport) A {
   ...
   template<typename T> bool func(T&) const;
}

Implementation:

template<typename T> bool A::func(T&) {...}

Due to some constraints, I can't define it the header. In the standalone library I get no build errors. But in the client application, built on the same platform using same compiler (x64 vs100), the linker error I get is:

error LNK2019: unresolved external symbol bool "public: bool __cdecl A::func(...)"

Appreciate any ideas on this. Thanks!

squashed.bugaboo
  • 1,338
  • 2
  • 20
  • 36
  • 2
    Same answer as [absolutely every other](http://stackoverflow.com/q/495021/596781) "my template code doesn't link" question on this site? – Kerrek SB Sep 20 '13 at 22:33

2 Answers2

0

Your template code will not be generated until you actually instantiate it using some data type. For every data type different code is generated by the compiler.

Therefore if you want to use templated code that other code parts shall be able to use with any data type then the template implementations needs to be provided inline (i.e. in a header file of some sort). Only this way the template can be instantiated for any unknown data types in other compilation units.

If you only need a small number of variants of the template, say for int and float then you can declare explicit template instantiations. These declarations cause the compiler to actually output the template code for the given data types whether they're needed or not in a compilation unit. Then you also need to add dllimport/dllexport statements (in case of Windows Visual Studio compilers) for ex-/importing that code in/from a DLL.

More about this can surely be found in other discussions and documentation.

gerrit zijlstra
  • 766
  • 4
  • 8
  • Thanks @zijlstra: Declaring in header is not an option for me. I'm having trouble understanding why it builds fine (same platform - x64 vs100) when building in-place (dll export symbol); but generates the linker error only building from client (dll import symbol). Also, I'm not sure I understood what you mean when you said to add dllimport/dllexport statement for 'that code'; I have for on the class. Do you mean, I need those symbols explicity even for the instantiation declarations? – squashed.bugaboo Sep 21 '13 at 02:16
  • If you want to understand more about that look for example [here](http://stackoverflow.com/questions/666628/importing-explicitly-instantiated-template-class-from-dll) – gerrit zijlstra Sep 21 '13 at 10:51
0

Make sure that your implemetation is in the same header (or it is taken in with some other #include statement) as the definition of the class. In this case it should work.

Kirill Kobelev
  • 10,252
  • 6
  • 30
  • 51