简体   繁体   中英

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 :)

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM