+ 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; }
1 Odpowiedź
+ 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.