Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does explicit template instantiation go in cpp or header file?

Tags:

Does explicit template instantiation go in cpp or header file?

like image 794
Avery3R Avatar asked May 03 '11 02:05

Avery3R


People also ask

Do templates have to be in header files?

To have all the information available, current compilers tend to require that a template must be fully defined whenever it is used. That includes all of its member functions and all template functions called from those. Consequently, template writers tend to place template definition in header files.

How do I explicitly instantiate a template?

To explicitly instantiate a template class function member, follow the template keyword by a declaration (not definition) for the function, with the function identifier qualified by the template class, followed by the template arguments.

Do you include the header file or the CPP file?

The basic idea that headers are only included and cpp files are only compiled. This will become more useful once you have many cpp files, and recompiling the whole application when you modify only one of them will be too slow. Or when the functions in the files will start depending on each other.

Why can templates be implemented in the header file C++?

Consequently, the compiler needs to have access to the implementation of the methods, to instantiate them with the template argument (in this case int ). If these implementations were not in the header, they wouldn't be accessible, and therefore the compiler wouldn't be able to instantiate the template.


2 Answers

Assuming by "explicit template instantiation" you mean something like

template class Foo<int>; // explicit type instantiation // or template void Foo<int>(); // explicit function instantiation 

then these must go in source files as they considered definitions and are consequently subject to the ODR.

like image 75
ildjarn Avatar answered Sep 25 '22 19:09

ildjarn


I've always done it in a cpp file. In a header, it would violate the one definition rule, at least (in the usual case) when the header was included in more than one cpp file.

like image 45
Jerry Coffin Avatar answered Sep 23 '22 19:09

Jerry Coffin