LearnFrenzy
Sign in Take a free test

Templates · Find the Error · Question 2

Error: a template using an operation the type lacks Answer, explanation & discussion

  • Find the error
  • Medium
  • 0 comments
  • Answer explained
  • Moderated community
Question 2 Back to Exercise

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;
}
  • 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!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links