Speed up development with full-stack environments for every branch.

Learn More

C++ Examples for Templated functions

290 Runs 1562 Views 310 Copies
Saved

Saved

tianxiasoft 13

tianxiasoft
published 4 years ago

#include <iostream>

using namespace std;

/******************************************************************************************/
/*  This example shows use of template function.  					                  */
/******************************************************************************************/

// template function that retrieves sum of array
template<class T> T sum(T a[], int length)
{
	T ret = a[0];
	for (int i = 1; i < length; i ++)
		ret += a[i];

	return ret;
}

int main(void) {
	int int_data[5];
	float float_data[5];
	int i = 0;

	// input 5 integers
	cout << "Input 5 integers" << endl;
	for (; i < 5; i++)
		cin >> int_data[i];
	// print sum of 5 integers
	cout << "Sum of above is " << sum(int_data, 5) << endl;

	// input 5 float numbers
	cout << "Input 5 floats" << endl;
	for (i = 0; i < 5; i ++)
		cin >> float_data[i];
	// print sum of 5 float numbers
	cout << "Sum of above is " << sum(float_data, 5) << endl;

	cin.get();
	return 0;
}
Please login/signup to get access to the terminal.

Your session has timed out.

Dismiss (the page may not function properly).