Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Non-template methods of a template class in .cpp file - Undefined reference?

I am aware that template functions must be defined in the header file, for some reason I forgot. However I believed that non-template functions, even if they belong to a template class, could be defined in a .cpp file. Is that allowed ? If not, why not ? Thank you :)

like image 599
Virus721 Avatar asked Sep 18 '25 21:09

Virus721


1 Answers

Actually, what must be defined in headers/at point of use (unless an explicit instantiation somewhere else happens), are "templated entities". There is no term like this in C++ so far, but proposals are in flight to add it to the language, since many rules apply to "templated entities" rather than just to templates.

See http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2016/p0391r0.html

The reason should be obvious. Just like templates, the members of templates can make use of the template parameters, so their source must be available for instantiation.

The trick to work around this for classes (if the member function does not use the template parameter) is to put the functions in a non-template base class and inherit that class from the class template.

like image 90
Johannes Schaub - litb Avatar answered Sep 21 '25 13:09

Johannes Schaub - litb