Card 1 / 7
Write one function that returns the larger of two values of the same type, for any type whose values compare with <.
left |
right |
max_value(left, right) |
|---|---|---|
3 |
7 |
7 |
7 |
3 |
7 |
-5 |
-9 |
-5 |
"apple" |
"banana" |
"banana" |
A function template opens with template <class T>; from there, every place the argument type appears — both parameters and the return type — is spelled T. Take the parameters as const T& so a std::string argument is not copied, and compare with < only, so the template works for any type that defines just that one operator.
// Write one function template that returns the larger of two values of the
// same type, for any type whose values compare with <.
//
// max_value(3, 7) -> 7
//
// Signature to write: T max_value(const T& left, const T& right)
template <class T>
T max_value(const T& left, const T& right) {
return left < right ? right : left;
}Card 2 / 7
Write a class template that stores two values of possibly different types, then give the same-type case a shorter name with an alias template.