rgk
rgk

Reputation: 866

Class generation when we pass a specific type to class template

I was reading this tutorial on Templates and when it came to function templates I found this snippet of code and text

template <class myType>
myType GetMax (myType a, myType b) {
return (a>b?a:b);
}

GetMax <int> (x,y);

When the compiler encounters this call to a template function, it uses the template to automatically generate a function replacing each appearance of myType by the type passed as the actual template parameter (int in this case) and then calls it. This process is automatically performed by the compiler and is invisible to the programmer.

So how does instantiation work out in the case of Class Templates? The documentation there did not throw any light on this topic. Does it happen when

  1. I create the object
  2. Call the function for the first time
  3. Every time I call the function

Can someone please throw some light on this topic

Upvotes: 1

Views: 72

Answers (1)

masoud
masoud

Reputation: 56479

It will be instantiated in compile-time when compiler finds out you used it for <int>. (Everything else is compiler's implementation specific)

Instantiating occurs once per template arguments in a translation unit.

Upvotes: 2

Related Questions