I have forgotten
my Password

Or login with:

  • Facebookhttp://facebook.com/
  • Googlehttps://www.google.com/accounts/o8/id
  • Yahoohttps://me.yahoo.com
Index » Programming » C/C++ »

john\′s Photo
25 Jul 06, 7:08PM
easy

template<class T>
void calculate(T x, T y)
{
  // calculate your area
  cout << (x*y);
  // calculate perimeter
  cout << (2*x+2*y);
}
 
int main()
{
// ... your code to input ..
  calculate(x,y);
}

The

bit defines a general type, T. For all practical purposes simply image the T is saying 'double', or
'float', or 'int'.. So everywhere you need a type within your calculate function of this generic
type, put T instead.
The neat bit is the compiler figures out what type to assign when compiling by looking at the type
of the variables you pass to the function.
 
 
\code
 
int x, y;
// assign values
calculate(x,y);  // T in the calculate function is a integer

float x, y;
// assign values
calculate(x,y);  // T in the calculate function is a float

etc.

Currently you need to be logged in to leave a message.