Here is a listing of C++ interview questions on “Simple String Template” along with answers, explanations and/or solutions:
1. What is a template?
a) A template is a formula for creating a generic class
b) A template is used to manipulate the class
c) A template is used for creating the attributes
d) A template is used to delete the class
Answer: a
Clarification: Templates are used for creating generic classes to handle different types in single classes.
2. Pick out the correct statement about string template.
a) It is used to replace a string
b) It is used to replace a string with another string at runtime
c) It is used to delete a string
d) It is used to create a string
Answer: b
Clarification: Every string template is used to replace the string with another string at runtime.
3. How to declare a template?
a) tem
b) temp
c) template<>
d) temp()
Answer: c
Clarification: template<> syntax is used.
An example for calculating max of two ints, floats, doubles, or any other number type where T indicates the type of the parameters passes.
template
T max(T a, T b){
return a > b? a : b;
}
4. What will be the output of the following C++ code?
-
#include -
using namespace std;
-
template <class T>
-
inline T square(T x)
-
{ -
T result; -
result = x * x;
-
return result;
-
};
-
template <>
-
string square<string>(string ss)
-
{ -
return (ss+ss);
-
};
-
int main()
-
{ -
int i = 4, ii;
-
string ww("A");
-
ii = square<int>(i);
-
cout << i << ii;
-
cout << square<string>(ww) << endl;
-
}
a) 416AA
b) 164AA
c) AA416
d) AA41A
Answer: a
Clarification: In this program, We are using two template to calculate the square and to find the addition.
Output:
$ g++ tem.cpp $ a.out 416AA
5. What will be the output of the following C++ code?
-
#include -
using namespace std;
-
template <typename T, typename U>
-
void squareAndPrint(T x, U y)
-
{ -
cout << x << x * x << endl;
-
cout << y << " " << y * y << endl;
-
};
-
int main()
-
{ -
int ii = 2;
-
float jj = 2.1;
-
squareAndPrint<int, float>(ii, jj);
-
}
a)
23 2.1 4.41
b)
24 2.1 4.41
c)
24 2.1 3.41
d) 2.1 3.41
Answer: b
Clarification: In this multiple templated types, We are passing two values of different types and producing the result.
Output:
$ g++ tem1.cpp $ a.out 24 2.1 4.41
