User Tools

Site Tools


haas:spring2015:common:cprogtemplates

Templates

Another abstraction provided by C++ are templates, which allows for a sort of generic use of functions with a range of variable types.

1
/*
 * average.cc - an example average program using templates
 *
 */
#include<iostream>
using namespace std;
 
template <class T>
void myaverage (T val1, T val2, T val3)
{
    T result;
    result = val1 + val2 + val3;
 
    cout << "First value is: " << val1 << endl;
    cout << "Second value is: " << val2 << endl;
    cout << "Third value is: " << val3 << endl;
 
    cout << "The sum of all three are: " << result << endl;
 
    cout << "The average of all three are: " << (T)(result/3) << endl;
}
 
int main()
{
    myaverage(3.1, 7.3, 1.7);
    myaverage(2, 4, 6);
    myaverage('~', '|', 'z');
    return 0;
}
haas/spring2015/common/cprogtemplates.txt · Last modified: 2013/04/24 15:01 by 127.0.0.1