0

Why will i use explicit instantiation of a function template, for a type? If I do not use explicit instantiation of the function, the template is used to create the necessary function then what is the use of explicit instantiation?

template <class Any>
void Swap (Any &, Any &);
// template prototype

template <> void Swap<job>(job &, job &);
// explicit specialization for job

int main(void)
{

template void Swap<char>(char &, char &); 
// explicit instantiation for char

short a, b;
Swap(a,b);
// implicit template instantiation for short

job n, m;
Swap(n, m);
// use explicit specialization for job

char g, h;
Swap(g, h);
// use explicit template instantiation for char

}

In the above eg. explicit instantiation is done for char type. What is the use of this?? If the compiler can make use of the template to make a fn for char type.

If there are any refrences that can help me clear my concept, pls do include those.

Suvarna Pattayil
  • 5,136
  • 5
  • 32
  • 59
  • To **Mr.Downvoter**, Please take the effort to leave behind a reason for your downvote. Incase it is because you find it a dupe, As far as i remember that question didnt show up when i made a search (or maybe because the title was made clear after i posted my question) – Suvarna Pattayil Apr 26 '13 at 19:15

1 Answers1

2

The definition of a template must be available in each translation unit that instantiates it. Typically, this is achieved by defining the template in a header; but in some circumstances you might not want to do that - perhaps you don't want your clients to see the source for the implementation.

Instead, you could declare the template in a header; then define it, and explicitly instantiate all the specialisations you need, in a source file.

Mike Seymour
  • 249,747
  • 28
  • 448
  • 644