Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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())?

like image 624
iBug Avatar asked Dec 30 '17 10:12

iBug


People also ask

Is it necessary to instantiate a template?

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).

Are templates instantiated at compile time?

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.

Can we see the template instantiated code by C++ compiler?

If your looking for the equivalent C++ code then no. The compiler never generates it.

What is the instantiation of the class template?

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.


2 Answers

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, [...]

like image 177
Oliv Avatar answered Oct 18 '22 03:10

Oliv


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.

like image 2
user0042 Avatar answered Oct 18 '22 03:10

user0042