0

C++: The compiler and function templates

 2 years ago
source link: https://www.programmerinterview.com/c-cplusplus/c-the-compiler-and-function-templates/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

How does the compiler deal with function templates in C++?

If you need a quick refresher on function templates then check out the previous example of function template usage in C++.

Does the compiler create separate definitions for all possible types for a function template?

When a programmer creates a function template, then what exactly is going on behind the scenes with the compiler? Well, the compiler does not create separate definitions for all possible types for the function template. Instead, the compiler does the smart thing and only creates definitions for the types that are actually used – so if a function template is called with an int and a float, then the compiler will create definitions for the function template with those 2 types and not other types like char or double.

An example will help clarify this. Suppose we have the following function template definition that is used to swap the values of 2 variables. As you can see, the function template is also called twice in the main function, but with 2 different types:

// the template prefix:
template<class T>
void swapVariables(T& var1, T& var2)
{
  T temp;
  temp = var1;
  var1 = var2;
  var2 = temp;
}

int main( )
{
  float float1 = 3.5, float2 = 5.6;
 //call to the function: 
 swapVariables(float1, float2);

  int int1 = 3, int2 = 5;
 //call to the function: 
 swapVariables(int1, int2);
}

In the function above, you can see the function swapVariables is called twice in the main function. So, what the compiler does is create 2 separate definitions of the swapVariables function – one for ints and the other for floats, since those are the only 2 types used when calling this function. The compiler will not produce definitions for every possible type – only the ones that are actually used!


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK