Q: 1 The keyword ‘template’ can be used for?
Creating reference.
Provide reusability.
Developing generic programming.
Creating template for further use.
[ Option C ]
In programming, we often need to write the same logic again and again for different data types. For example, a function to add two integers and another function to add two floating-point numbers. Writing separate functions for each data type leads to code duplication.
To solve this problem, C++ provides the concept of generic programming using the template keyword.
A template allows us to write one function or one class that can work with any data type. The actual data type is decided at compile time when the program is compiled.
Thus, the template keyword is mainly used for developing generic programming, which helps in:
#include<iostream>
using namespace std;
template<class T>
T add(T a,T b)
{
return a+b;
}
int main()
{
cout<<add(2,5)<<endl;
cout<<add(2.5,6.3)<<endl;
return 0;
}
OUTPUT
7
8.8
Q: 2 Complete the code for overloaded template by replacing the ABCD:
#include<iostream>
using namespace std;
template <class X>
void f (X a)
{
cout<<”Inside ”;
}
ABCD
{
cout<<”Outside ”;
}
int main()
{
f (10);
f (10,20);
return 0;
}
template void f (X a, Y b)
<class X, class Y>
template <class X, class Y>
template f (X a, Y b)
template <class X, class Y>
void f (X a, Y b)
[ Option D ]
The original function template is declared for one argument as:
template <class X>
void f(X a) {
cout << "Inside ";
}
In main(), the code calls:
f(10); // Calls the first template function.
f(10, 20); // Needs a new template function for two arguments.
The second call f(10, 20) cannot use the first template because it only takes one argument. Therefore, we need to overload the template for two arguments of possibly different types as:
template <class X, class Y>
void f(X a, Y b) {
cout << "Outside ";
}
Thank you so much for taking the time to read my Computer Science MCQs section carefully. Your support and interest mean a lot, and I truly appreciate you being part of this journey. Stay connected for more insights and updates! If you'd like to explore more tutorials and insights, check out my YouTube channel.
Don’t forget to subscribe and stay connected for future updates.