Search code examples
c++template-instantiation

Is it possible that a compiled program does not contain an instantiated template class?


Consider this code:

template <typename T>
class A {
    T x;
    // A bunch of functions
};

std::size_t s = sizeof(A<double>);

Assume the sizeof operator is the only place where an instantiation of A<double> is required. Is it possible that the compiled program does not contain relevant code for A<double> (e.g. A<double>::~A())?


Solution

  • The class will be instantiated, but the compiler must not instantiate any member function definition, [temp.inst]/1:

    [...] the class template specialization is implicitly instantiated when the specialization is referenced in a context that requires a completely-defined object type[...]

    [temp.inst]/2:

    The implicit instantiation of a class template specialization causes the implicit instantiation of the declarations, but not of the definitions, default arguments, or noexcept-specifiers of the class member functions, [...]