function templates

Function Templates

By adding template to the function definition, we can turn a function into a generic function. Absolute value is a good example of a generic function that can take multiple data types.

template <class T>
T absValue(T x){
    if(x < 0){
        return -x;
    }
    return x;
}


int main()
{
    int x = 2563;
    int y = -2914;
    int z = 47.5432;

    cout << "The absolute value of " << x << " is " << absValue(x) << endl;

    cout << "The absolute value of " << y << " is " << absValue(y) << endl;

    cout << "The absolute value of " << z << " is " << absValue(z) << endl;

    return 0;
}

Whenever we see T in a C++ program, chances are we are looking at a template. The use of T as a template parameter name is simply a convention.

When writing templates the problem is that we do not know what type or types T will actually be. So the function must be generic.

If a template takes multiple arguments, we should separate the arguments with a comma.

//returns a negative value if x is less than y
//0 if x and y are roughly the same
//a positive number if x is greater than y
template <class T, class U>
int compareValues(T x, U y){
    double rValue = x - y;
    double cValue = rValue;

    if(cValue < 0){
        cValue *= -1;
    }

    if(cValue < .000000001){
        return 0;
    }
    return rValue;
}

int main()
{
   int x = 47;
   double y = 19.99;
   char z = 's';

   if(compareValues(x, y) < 0){
    cout << x << " is greater than " << y << endl;
   } else {
    cout << y << " is greater than " << x << endl;
   }

   if(compareValues(y, z) < 0){
    cout << y << " is less than " << z << endl;
   } else {
    cout << y << " is greater than " << z << endl;
   }

    return 0;
}