PDA

View Full Version : Use of Template in C++


tojunaid
07-25-2006, 07:51 PM
i am quite new in C++, therefor i need some help, i have to write a code for calculating area and perimeter of rectangle, which seems to be quite a simple one, like i wrote

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 it says to calculate the same by using the function template template<class T>. 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 give me the concept of this TEMPLATE, i mean how to use this in calculating area and perimeter

thankx,

oracleguy
07-25-2006, 10:07 PM
Here is a page I found on templates that has some information: http://www.is.pku.edu.cn/~qzy/cpp/vc-stl/templates.htm

Basically the first thing you need to do is make the part where it calculates and displays the result into a function. Since right now you are using floats, you're function prototype might look like:

calculate(float x, float y)

What you need to do next (per the instructions) is make that function templated so you can pass in whatever you want data-type wise, integers, doubles, floats. Instead of making say 3 different versions of the same function, templating allows you to write on copy and the compiler will make the appropriate ones for the data types used.