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()
)?
In order for any code to appear, a template must be instantiated: the template arguments must be provided so that the compiler can generate an actual class (or function, from a function template).
Templates are instantiated in the process of converting each translated translation unit into an instantiation unit. A translation unit is essentially a source file. A translated translation unit (try to say that three times fast) is the output from compilation without templates instantiated.
If your looking for the equivalent C++ code then no. The compiler never generates it.
The act of creating a new definition of a function, class, or member of a class from a template declaration and one or more template arguments is called template instantiation.
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, [...]
Is it possible that the compiled program does not contain relevant code for
A<double>
(e.g.A<double>::~A()
)?
Sure that's possible.
std::size_t s = sizeof(A<double>);
is just a compile time operation, and doesn't need any runtime instance of A<double>
, so there's no need for constructors, destructors, or other relevant code.
Even if there would be explicit instantiations of template function code like follows
if(sizeof(A<double>) <= 4) {
A<double> a; // Instantiation of constructor and destructor
a.x = 3.5;
}
the compiler is allowed to optimize that code away.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With