Software & Finance





C++ - Function Templates





A function template can be used when it does the work based on the generic data types. It is often used to write an algorithms when the program flow would be sample but the data type differs on case to case.

A sample function template is given below as you see it does the simple addition on generic data type called class which will defined later. When we start using this template function, then compiler will generate a function with actual data types. In case, we are using this function on 3 different data types, then we will have 3 different sets of function at run time. At run time, there will not be any code call "template". All templates will be replaced with actual arguments during compile time itself.

Many class libraries and algorithms are developed using templates. It provides the operation on generic data type. Using templates will not increase or decrease at run time. Code maintenance will be easier by using templates.

In the following example, we will have two sets of add functions generated by compiler one for int and the other for double. In case, we are not using this template function, then compiler will not generate even one function.


Source Code


template

T add(T x, T y)

{

    return x + y;

}

 

int _tmain(int argc, _TCHAR* argv[])

{

 

    int c1 = add((int)sz1, (int)sz2);

    double c2 = add((double)sz1, (double)sz2);

 

    int (*fp1)(int, int);

    double (*fp2)(double, double);

    fp1 = add;

    fp2 = add;

 

    int c3 = fp1((int)sz1, (int)sz2);

    int c4 = fp2((double)sz1, (double)sz2);

}

Output


None