After few weeks break, I'm trying to expand and extend my knowlege of templates with the book Templates – The Complete Guide by David Vandevoorde and Nicolai M. Josuttis, and what I'm trying to understand at this moment is explicit instantiation of templates.
I don't actually have a problem with the mechanism as such, but I can't imagine a situation in which I would like or want to use this feature. If anyone can explain that to me I will be more than grateful.
Directly copied from https://docs.microsoft.com/en-us/cpp/cpp/explicit-instantiation:
(For instance, libstdc++ contains the explicit instantiation of
std::basic_string<char,char_traits<char>,allocator<char> >
(which isstd::string
) so every time you use functions ofstd::string
, the same function code doesn't need to be copied to objects. The compiler only need to refer (link) those to libstdc++.)It depends on the compiler model - apparently there is the Borland model and the CFront model. And then it depends also on your intention - if your are writing a library, you might (as alluded above) explicitly instantiate the specializations you want.
The GNU c++ page discusses the models here https://gcc.gnu.org/onlinedocs/gcc-4.5.2/gcc/Template-Instantiation.html.
If you define a template class that you only want to work for a couple of explicit types.
Put the template declaration in the header file just like a normal class.
Put the template definition in a source file just like a normal class.
Then, at the end of the source file, explicitly instantiate only the version you want to be available.
Silly example:
Source:
Main