What is a template?

Templates allow to create generic functions that admit any data type as parameters and return value without having to overload the function with all the possible data types. Until certain point they fulfill the functionality of a macro. Its prototype is any of the two following ones:

template identifier> function_declaration; template identifier>
function_declaration;


The only difference between both prototypes is the use of keyword class or
typename, its use is indistinct since both expressions have exactly the same
meaning and behave exactly the same way.

Showing Answers 1 - 3 of 3 Answers

sankar

  • Jun 27th, 2006
 

template is used for creating generic functions as well as data members.

  Was this answer useful?  Yes

A template parameter is a special kind of parameter that can be used to pass a type as argument: just like regular function parameters can be used to pass values to a function, template parameters allow to pass also types to a function. These function templates can use these parameters as if they were any other regular type.

The format for declaring function templates with type parameters is:

template <class identifier> function_declaration;
template <typename identifier> function_declaration;


lets take an example to understand TAMPLATES




#include <iostream>
using namespace std;

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

int main () {
int i=5, j=6, k;
long l=10, m=5, n;
k=GetMax<int>(i,j);
n=GetMax<long>(l,m);
cout << k << endl;
cout << n << endl;
return 0;
}

MCBod

  • Mar 31st, 2010
 

A template is a function that is defined without template parameters, being parameters that have an undefined type. The logic of the function must be executable for all possible data types e.g. using standard operators.

The template can then be invokes for a speciic set of parameters, by defining the data types for which we are calling the function

One obvious example may be max function relying on the use of a > operators for whatever data types are passed to it

  Was this answer useful?  Yes

Give your answer:

If you think the above answer is not correct, Please select a reason and add your answer below.

 

Related Answered Questions

 

Related Open Questions