Q:

What is a template function in c++?

0

What is a template function?

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

Using the template we can create a generic function that will perform the set of operations on different data types. The type of data that the function will operate upon is passed to it as a parameter. Let see an example code,

In the below code, I am creating a generic function using the template that will find the smallest number among two passed numbers.

#include <iostream>
using namespace std;
template <typename T>
T findMinNumber(T x, T y)
{
    return (x < y)? x: y;
}
int main()
{
    cout << findMinNumber<int>(2, 7) << endl; // Call findMinNumber for int
    cout << findMinNumber<double>(3.5, 7.0) << endl; // call findMinNumber for double
    cout << findMinNumber<char>('d', 'p') << endl; // call findMinNumber for char
    
    return 0;
}

Output:

2
3.5
d

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

C++ Interview Questions For Experienced

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
What is the difference between function overloadin... >>
<< What is the difference between a concrete class an...