0

I assume the answer will be simple, but I cannot figure out a solution.

I have a class to be used as an interface in the h-file:

template <typename T>
class MyInterface
{
public:
  MyInterface();
};

In the cpp-file it is:

#include "MyInterface.h"
template<typename T>
MyInterface<T>::MyInterface()
{
}

My class using the interface is:

class Test : MyInterface<int>
{
};

When compiling I get the error, the ctor of MyInterace is not declared.

unresolved external symbol "public: __thiscall MyInterface::MyInterface(void)" (??0?$MyInterface@H@@QAE@XZ) referenced in function "public: __thiscall Test::Test(void)"

Having the ctor declared in the h-file, it compiles.

Wernfried
  • 206
  • 3
  • 9
  • Can someone answer please? – Wernfried Dec 05 '21 at 23:04
  • Does this answer your question? [Why can templates only be implemented in the header file?](https://stackoverflow.com/questions/495021/why-can-templates-only-be-implemented-in-the-header-file) – Bob__ Dec 05 '21 at 23:07

1 Answers1

0

Templates are instantiated on the fly. If you want to put the constructor in a cpp file, you must specialize it.

#include "MyInterface.h"
template<>
MyInterface<int>::MyInterface()
{
}

Otherwise, it must be in a header as all template functions are managed inline.

If you'd like to keep code organized, make an inl file, with all the function bodies of your code, and then include it at the bottom of your header.

// MyInterface.h
template <typename T>
class MyInterface
{
public:
  MyInterface();
};

#include "MyInterface.inl"
// MyInterface.inl
template<class T>
MyInterface<T>::MyInterface()
{
}
j__
  • 632
  • 4
  • 18