How to Create a Basic Math Template in C++ - dummies

# How to Create a Basic Math Template in C++

With a math template, you usually need access to a wealth of calculations but may only use one or two of those calculations at a time. For example, if someone is calculating your mortgage, he or she doesn’t need to know the amortization calculation. However, the person might need the amortization calculation when working with the next customer.

In short, the calculations all have a purpose and you need them all, but you don’t need them all at the same time. Because of the way you use math templates, they work best as a series of function templates. The MathTemplate example shows how to create the series of functions.

#include <iostream>
#include <cmath>
using namespace std;
template<typename T>
T Area(T height, T length)
{
return height * length;
}
const double PI = 4.0*atan(1.0);
template<typename T>
{
double result;
// This version truncates the value.
return (T)result;
}
template<typename T>
T TriangleArea(T base, T height)
{
double result;
result = base * height * 0.5;
return (T)result;
}
int main()
{
cout << "4 X 4 Areas:" << endl;
cout << "Square: " << Area<int>(4, 4) << endl;
cout << "Circle: " << CircleArea<int>(2) << endl;
cout << "Triangle: " << TriangleArea<int>(4, 4) << endl;
cout << "Using a value of pi of: " << PI << endl;
return 0;
}

The calculations could consist of any math calculation — the point of the example is that using functions makes each of the calculations discrete, easy to use, and easy to manage. When you run this example, you see the following output:

4 X 4 Areas:
Square: 16
Circle: 12
Triangle: 8
Using a value of pi of: 3.14159

Note that CircleArea<int>(2) uses half the value of the other calculations as input. That’s because you calculate the area of a circle using the equation pi x r2.

For consistency, you could change the circle equation to read like this: