vendredi 30 avril 2021

When does instantiation happens for explicit instantiation of a function template

Hi i am trying to learn about explicit instantiation. And so reading different examples but in one example have some doubts. The example is given below and i have 2 doubts in this particular example.

File Application.cc contains:

extern template int compare(const int&, const int&);
int i = compare(a1[0], a2[0]);// instantiation will appear elsewhere

File templateBuild.cc contains:

template int compare(const int&, const int&);

Also note that the function template compare is:

template<typename T, typename F = less<T>>
int compare(const T &v1, const T &v2, F f = F())
{
  if (f(v1,v2)) return -1;
  if (f(v2,v1)) return 1;
  return 0;
}

My questions are as follows:

  1. As you can see in the Application.cc file in the 2nd line it is written(as a comment) that instantiation will appear elsewhere. But here we are using the template function as int i = compare(a1[0], a2[0]); and we know that whenever we use a template function the compiler will instantiate it. So why is that comment written there? Also in the explanation it is written that

When the compiler sees an instantiation definition (as opposed to a declaration), it generates code. Thus, the file templateBuild.o will contain the definitions for compare instantiated with int.

So my question is if the compiler generates code whenever it sees an instantiation definition and so templateBuild.o will contain the definition of compare instantiated with int then how can we use compare() in the Application.cc file using compare(a1[0], a2[0]);? I mean the compare() template is not yet instantiated so how can we use it before it is instantiated?

  1. My 2nd question is that where should i write(put) the content of the compare() template. For example in a header file or in the Application.cc file? By the content of the compare() template i mean the 3rd block of code that i have given in the example.

Aucun commentaire:

Enregistrer un commentaire