C++ Programming

Template Class

C plus plus example for template class

12/5/2019
0 views
template-class.cppCPP
#include<iostream>
using namespace std;

template <class temp>
class arraySum {
	int size;

	/* 'temp' type list */
	temp *list;
	public:
		arraySum(temp *a) {
			list = a;
			/* Get size of the array */
			size = (sizeof(a)/sizeof(*a));
		}

		/* 'temp' type binary operator overloading */
		temp operator+(arraySum &array) {
			temp result=0;
			for(int i = 0; i <= size; i++)
				result += this->list[i] + array.list[i];
			return result;
		}
};

int main() {
	int a[3] = {1,2,3};
	int b[3] = {4,5,6};

	/* integer type 'arraySun' object */
	arraySum <int> array1(a);
	arraySum <int> array2(b);

	/* perform sum of two integer array using binary operator overloading */
	int isum = array1 + array2;
	cout << "Sum of two integer array: " << isum << endl;

	float x[3] = {1.11,2.43,3.01};
	float y[3] = {4.95,5.21,6.59};

	/* float type 'arraySun' object */
	arraySum <float> array3(x);
	arraySum <float> array4(y);

	/* perform sum of two float array using binary operator overloading */
	float fsum = array3 + array4;
	cout << "Sum of two float array: " << fsum << endl;
	return 0;
}



/* Output */
Sum of two integer array: 21
Sum of two float array: 23.3
cpptemplate classbinary operator overloadingC plus plus

Related Examples