Search code examples
c++templatesexplicit-instantiation

When do we need to explicitly instantiate a template function?


Let's say we have a template function:

template <class T> T max(T a, T b) { return a > b ? a : b; }

Since the compiler doesn't perform any implicit type conversion during template argument deduction, we can invoke max(2, 5.5) in these two ways:

  1. Using casting : max(static_cast<float>(2), 5.5f);
  2. Using explicit template instantiation : max<float>(2, 5.5);

Second case makes sense to me, but when do we do the explicit template instantiation in the given below way (instantiating without invoking the function max with char type):

template char max(char a, char b);

What do we achieve out of it?


Solution

  • If you are writing a library then the templates not invoked by the library's code will not be implemented, therefore the library may be missing some functions that you intended to provide. The explicit instantiation will force the compiler to create an implementation for the specified template, even if no calls to it have been made.

    When you finally link your library with the client application then the linker will find the implementation for the types that your library supports.

    Maybe an explanation from a native English speaker will be clearer: https://learn.microsoft.com/en-us/cpp/cpp/explicit-instantiation