Computer Language/C++

[C++] idea of Template & Function Template

정우섭 2020. 6. 27. 21:13

Function Template

 

It's a tool for making a function which needs to be called in many different types.

 

  //for example
 int Add(int num1, int num2)
{
	return num1 + num2;
}

 

This function is for adding int type of variables.

 

Let's change it into a function template.

 

template <class T>
T Add(T num1, T num2)
{
  return num1 + num2;
}

 

  •  template <class T> / template <typename T>

Means declare the following function into template by using 'T'.

(You can use both class and typename, they're all same.)

 

  • T

Means the type will not be decided now, so call function with a type written instead of 'T'.

(You can name anything, not only 'T'.)

 

  •  funtion template & template function

function template : The declaration of template with 'template <class -->'.

 * Function template is a mold for template function, template itself is not a function.

template <class T>
T Add(T num1, T num2)
{
  return num1 + num2;
}

template function : Since the function template is called with a type metioned, template function is built.

cout<< Add<int>(1, 9) <<endl;
cout<< Add<double>(1.2, 3.4) <<endl;

Functions built by Compiler

int Add(int num1, int num2)
{
  return num1 + num2;
}
double Add(double num1, double num2)
{
  return num1 + num2;
}

 

When you declare function template, compiler will build right functions following types you called in the code.

 

#include <iostream>
using namespace std;

template <typename T>

T Add(T num1, T num2)
{
	return num1 + num2;
}

int main(void)
{
	cout<< Add<int>(1, 9) <<endl;
	cout<< Add<double>(1.2, 3.4) <<endl;
	cout<< Add<int>(5.6, 7.8) <<endl;
	cout<< Add<double>(1.23, 4.56) <<endl;
}

Result

10
4.6
13
5.78

In the moment that the compiler compiles line13 it builds a function like this.

int Add(int num1, int num2)
{
  return num1 + num2;
}

In line15, the compiler doesn't build same function again, it just use the function already built at line13.

 

Same at line14, line16.

double Add(double num1, double num2)
{
  return num1 + num2;
}

* When the compiler calls a template declared function, it builds a function into the called type.

And when the same type is called again, the compiler just calls the same function again.

It doesn't build another one, so one function per type.

 

* The function is build while compiling so compilation speed goes down.

  But execution speed is same.

 

 

 

Declare template function for more than two types

#include <iostream>
using namespace std;

template <class T1, class T2>
void ShowData(double num)
{
	cout<<(T1)num<<", "<<(T2)num<<endl;
}

int main(void)
{
	ShowData<char, int>(65);
	ShowData<char, int>(67);
	ShowData<char, double>(68.9);
	ShowData<short, double>(69.2);
	ShowData<short, double>(70.4);
	return 0;
}

Result

A, 65
C, 67
D, 68.9
69, 69.2
70, 70.4

 

 

 

 

 

 

 

 

[참고자료]

- 윤성우의 열혈 C++ 프로그래밍