C++ Function Templates





C++ Function Templates:

In functions overloading, more than one function with same name are declared and defined. This makes the program more complex and lengthy. To overcome this problem, function template is used.

In a function template, a single type less function is defined such that arguments of any standard data type can be passed to the function.

The general syntax of a function template is:

template < class T >
T f-name ( T argument(s) )
statement (s) ;
}

template: The keyword template is used to define the function template.

class: In a function template a general data name is defined by using the keyword “class”. In the above syntax, it is represented by the word “T”. Any character or word can he used after the keyword “class” to specify the general data name.

f-name: It specifies the name of the function.

argument (s): These are the arguments that are to be passed to the function. The arguments are declared of type T. As explained earlier, the type T specifies any standard data type.

statement (s): It specifies the actual statements of the function.

For example, to write a function to calculate a sum of three values either integers or floating-points, the function template is written as:

template < class T >
T sum (T a, T b, T c)
{
return a + b + c;
}

Program:

Write a program to calculate and print the sum of three integer and floating-point values. Use the function template.

#include < iostream.h >
template < class T >
T sum (T a, T b, T c)
{
return a + b + c;
}
main ( )
cout << “Sum of 3 integer values  =” << sum (87, 316, 9) cout << “Sum of 3 float values =” << sum (2.6, 3.9, 6.l);

}

Other Topics



Comments are closed.

Translator

    Translate to:

Get Adobe Flash playerPlugin by wpburn.com wordpress themes