0

I read that its possible to create template method. I have something like this in my code

File : Student.h

class Student
{
public:
    template<class typeB> 
    void PrintGrades();
};

File: Student.cpp

#include "Student.h"
#include <iostream>

template<class typeB> 
void Student::PrintGrades()
{
    typeB s= "This is string";
    std::cout << s;
}

Now in main.cpp

Student st;
st.PrintGrades<std::string>();

Now I get a linker Error:

Error   1   error LNK2019: unresolved external symbol "public: void __thiscall Student::PrintGrades<class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> > >(void)" (??$PrintGrades@V?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@@Student@@QAEXXZ) referenced in function _main

Any suggestion on what I might be doing wrong ?

MistyD
  • 16,373
  • 40
  • 138
  • 240
  • I dont see how this is a duplicate. That post talks about template classes and not template methods – MistyD Oct 06 '13 at 19:53

1 Answers1

1

The template is not instantiated anywhere, causing a linker error.

For templates defined in the header, the compiler will generate the instantiation by itself, because it has access to its definition. However, for templates defined in the .cpp file, you need to instantiate them yourself.

Try adding this line to the end of your .cpp file:

template void Student::printGrades<std::string>();
Krzysztof Kosiński
  • 4,225
  • 2
  • 18
  • 23