template program | Sololearn: Learn to code for FREE!

+1

template program

template <class T> T sum(T a, T b) {//why did we write here T sum(T a,T b)? return a+b; } int main () { int x=7, y=15; cout << sum(x, y) << endl; }

10/25/2017 1:59:22 PM

Shivani Goyal

1 Answer

New Answer

+5

Templates allow you use declare functions that can work with any data type by declaring a temporary class or typename and then substituting it with the type of the arguments passed during compilation. Thus, T is a temporary class that you use to create variables that can store variables of any data type. Thus, you pass T, so that the function can work with ints, chars, floats, strings, classes, etc.