0

I am writing a Template Class with a public method. The definition of the method is in the .cpp file for the class. When I build the project, the Linker throws a LNK2019 error (Unresolved external symbol) for that method. If I place the definition in the .h file, it links and runs.

Is there a problem with putting a template class methods in the .cpp file? Non-template classes work just fine. I can't seem to find anything about a limitation on that. I am building using Visual Studio 2019.

Here are a couple of simple files to show the problem (MyTemplate.h, MyTemplate.cpp, and main.cpp):

#include <iostream>

using namespace std;

template<typename M> 
class MyTemplate
{
public:
    void ShowText();
};

class NonTemplate
{
public:
    void ShowText();
};
#include "MyTemplate.h"

template<typename M>
void MyTemplate<M>::ShowText()
{ 
    cout << "Successful!" << endl; 
}



void NonTemplate::ShowText()
{ 
    cout << "NonTemplate Success!" << endl; 
}
#include "MyTemplate.h"

int main()
{
    MyTemplate<int> mt;
    mt.ShowText();

    NonTemplate nt;
    nt.ShowText();
}
DaveC
  • 1

0 Answers0