Each C++ program contains a template mistake that the compiler rejects. Choose the option that names the real problem.
Question 1Easy
The program below does not compile. Which statement correctly describes the problem?
main.cpp
#include <iostream>
template <typename T>
T smaller(T a, T b) { return a < b ? a : b; }
int main() {
std::cout << smaller(10, 7.5) << '\n';
return 0;
}
A< cannot compare numbers
BT is deduced as int from 10 and double from 7.5; the conflict makes deduction fail – use smaller<double>(10, 7.5) or two type parameters
Csmaller must be inline
DTemplates cannot return T
Correct Answer: Option B
Template deduction does not perform the usual arithmetic conversions.
The program below does not compile. Which statement correctly describes the problem?
main.cpp
#include <iostream>
#include <string>
struct Student { std::string name; int marks; };
template <typename T>
T best(T a, T b) { return a > b ? a : b; }
int main() {
Student x{"Asha", 91}, y{"Ravi", 78};
std::cout << best(x, y).name << '\n';
return 0;
}
AStudent needs a constructor
Bbest uses a > b, but Student has no operator>; define one (or <=>) or pass a comparator
CTemplates cannot take structs
Dname must be public
Correct Answer: Option B
A template only compiles for types that support every operation it uses. A concept such as std::totally_ordered would make the error point at the call.
BLabel<int> was already implicitly instantiated in show(), so an explicit specialisation declared afterwards is an error; declare the specialisation before any use
CSpecialisations must be in main
Dint cannot be specialised
Correct Answer: Option B
Specialisations must be visible before the first use that would cause implicit instantiation.
We use Google Analytics cookies to see how LearnFrenzy is used and make it better, and Google AdSense to keep it free.
No analytics or ad cookies are set until you accept. Privacy Policy
·