Templates
- What is the output of this program?
#include <iostream>
#include <string>
#include <cstring>
using namespace std;
template <class type>
type Maximum(const type value1, const type value2)
{
cout << "No Specialization";
return value1 < value2 ? value2 : value1;
}
template <>
const char *Maximum(const char *value1, const char *value2)
{
return (strcmp(value1, value2) < 0) ? value2 : value1;
}
int main()
{
string S1 = "class", S2 = "template";
const char *value3 = "Interveiw";
const char *value4 = "Mania";
const char *q = Maximum(value3, value4);
cout << q << endl;
return 0;
}
-
View Hint View Answer Discuss in Forum
NA
Correct Option: D
In this program, We are computing the result in the specialized block of the program.
- How many kinds of parameters are there in C++?
-
View Hint View Answer Discuss in Forum
NA
Correct Option: A
There are three kinds of parameters are there in C++. They are type, non-type, template.
- What is the output of this program?
#include <iostream>
using namespace std;
template <typename T = float, int count = 3>
T Multiply(T num1)
{
for(int kk = 0; kk < count; kk++)
{
num1 = num1 * num1;
}
return num1;
};
int main()
{
float num2 = 1.25;
cout << num2 << " " << Multiply<>(num2) << endl;
}
-
View Hint View Answer Discuss in Forum
NA
Correct Option: D
In this program, We specify the type in the template function. We need to compile this program by adding -std=c++0x.
- What is the output of this program?
#include <iostream>
using namespace std;
template <class T>
inline T square(T n1)
{
T Output;
Output = n1 * n1;
return Output;
};
template <>
string square<string>(string Str)
{
return (Str + Str);
};
int main()
{
int k = 4, kk;
string bb("B");
kk = square<int>(k);
cout << k << ": " << kk;
cout << square<string>(bb) << ":" << endl;
}
-
View Hint View Answer Discuss in Forum
NA
Correct Option: B
Template specialization is used when a different and specific implementation is to be used for a specific data type. In this program, We are using integer and character.
- Which is called on allocating the memory for the array of objects?
-
View Hint View Answer Discuss in Forum
NA
Correct Option: C
When you allocate memory for an array of objects, the default constructor must be called to construct each object. If no default constructor exists, you’re stuck needing a list of pointers to objects.