Question 2
Back to Exercise
The program below does not compile. Which statement correctly describes the problem?
#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;
}
- A Student needs a constructor
- B best uses a > b, but Student has no operator>; define one (or <=>) or pass a comparator Correct
- C Templates cannot take structs
- D name 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.
Discussion & Comments 0
Share your method, a shortcut, or ask about a step you didn't follow.
No comments yet. Be the first to share your solution!