I have a C++ template class that gets instantiated with 3 different type parameters. There’s a method that the class needs to have for only one of those types and that isn’t ever called with the two other types.
Will object code for that method be generated thrice (for all types for which the template is instantiated), or is object code generated only once (for the type with which it is actually used)?
Virtual member functions are instantiated when a class template is instantiated, but non-virtual member functions are instantiated only if they are called.
This is covered in [temp.inst] in the C++ standard (In C++11, this is §14.7.1/10. In C++14, it is §14.7.1/11, and in C++17 it is §17.7.1/9. Excerpt from C++17 below)
Also note that it is possible to instantiate a class template even if some of the member functions are not instantiable for the given template parameters. For example:
This is valid, even though Xyzzy::CallFoo() is not instantiable because there is no such thing as BarOnly::foo(). This feature is used often as a template metaprogramming tool.
Note, however, that ‘instantiation’ of a template does not directly correlate to how much object code gets generated. That will depend upon your compiler/linker implementation.