c++ - How to call a template Method -
this question has answer here:
i read possible create template method. have in 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 string"; std::cout << s; }
now in main.cpp
student st; st.printgrades<std::string>();
now 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 might doing wrong ?
the template not instantiated anywhere, causing linker error.
for templates defined in header, compiler generate instantiation itself, because has access definition. however, templates defined in .cpp file, need instantiate them yourself.
try adding line end of .cpp file:
template void student::printgrades<std::string>();
Comments
Post a Comment