2

Inside a library I have the following template class definition (this is a useless template class, it's just an example to keep the code short)

Lib.h

#ifdef PTRTESTLIB_EXPORTS
#define PTRTESTLIB_API __declspec(dllexport)   
#else  
#define PTRTESTLIB_API __declspec(dllimport)   
#endif 

template<class T> class PTRTESTLIB_API TemplateType
{
public:
    TemplateType() {}
    TemplateType(T e) : elem(e) {}
private:
    T elem;
};

In another project I want to use this template class. So, I import the Mylibrary.lib and include the necessary header file.

AnotherProject\Tester.cpp

#include <TestLib/Lib.h>

int main()
{
    TemplateType<double> d;
}

The compiler gives me the following error

1>------ Build started: Project: TesterClass, Configuration: Debug Win32 ------
1>TesterClass.cpp
1>TesterClass.obj : error LNK2019: unresolved external symbol "__declspec(dllimport) public: __thiscall TemplateType<double>::TemplateType<double>(void)" (__imp_??0?$TemplateType@N@@QAE@XZ) referenced in function "void __cdecl testPtrTestLib(void)" (?testPtrTestLib@@YAXXZ)
1>E:\Metrostaff_Software\ArcoCAD_Inspection\Sources\TesterClass\Debug\TesterClass.exe : fatal error LNK1120: 1 unresolved externals
1>Done building project "TesterClass.vcxproj" -- FAILED.
========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========

The only way to use the template class is to define in Lib.h

template class TemplateType<double>;

or

use this class template at least one time in the code of the library.

Is there a way to write a class template inside a library without knowing which will be it's specialization?

Thank you

Davide
  • 43
  • 7
  • 4
    Don't put the `declspec` stuff on template classes (it essentially tells the compiler to _not_ instantiate the template when user code uses it). The code should work if you get rid of that. Now, if there actually is a `Lib.cpp` that implements the template then you're out of luck - templates that have to accept arbitrary user types have to be in the header (again, without any export/import stuff). – Max Langhof Dec 16 '19 at 16:45
  • @MaxLanghof thank you! Your suggestion to remove the declspec fixed my problem and now I understand why it didn't work – Davide Dec 16 '19 at 16:56
  • FWIW I disagree with the close reason. The dupe doesn't apply to the question as written. Close-voters, please make sure to read carefully instead of pattern matching on "template" and "undefined reference". – Max Langhof Dec 16 '19 at 16:57

1 Answers1

0

Try to eliminate declspec in the template class. It should works.

Zig Razor
  • 3,381
  • 2
  • 15
  • 35