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++ »

how to use TEMPLATE in C++

abujunad\′s Photo
25 Jul 06, 5:58PM
(1 reply)
how to use TEMPLATE in C++
I am new in C++, and learning the langauge by my self only, while practicing i come across one question for which i have no idea, the question is to calculate area and perimeter of rectangle, the code i wrote was

#include <iostream> using namespace std; int main () { // declaration of variables float length; //length of a rectangle float width; //width of a rectangle float area; //area of a rectangle float perim; //perimeter of a rectangle // prompt for and read the input values cout << "Enter the length of the rectangle" << endl; cin >> length; cout << "Enter the width of the rectangle" << endl; cin >> width; //Calculate the area and the perimeter area = length*width; perim = 2.0*length + 2.0*width; //Display the result cout << "The area is " << area << endl; cout << "The perimeter is " << perim << endl;

return 0;

}

BUT I WHAT I NEED IS

The program will read the values of length and width from the user trough keyboard and passes these values to the function calculate(T x, T y). The function calculates the area and perimeter of the rectangle and displays the result on the screen. The function returns no value.

Can someone HELP?

thankx

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

template&lt;class T&gt;
void calculate&#40;T x, T y&#41;
&#123;
  // calculate your area
  cout &lt;&lt; &#40;x*y&#41;;
  // calculate perimeter
  cout &lt;&lt; &#40;2*x+2*y&#41;;
&#125;
 
int main&#40;&#41;
&#123;
// ... your code to input ..
  calculate&#40;x,y&#41;;
&#125;

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&#40;x,y&#41;;  // T in the calculate function is a integer

float x, y;
// assign values
calculate&#40;x,y&#41;;  // T in the calculate function is a float

etc.

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