ProblemsTemplatesOne maxOf for every type
NoviceTemplates

One maxOf for every type

Context

utils.h is home to maxInt, maxDouble and maxString, written by a man who 'didn't trust templates' — he's gone, the distrust remains. Today you need max for a new type. Don't write copy number four — write one template and delete three.

Task

Implement maxOf(a, b) as a single function template that returns the larger of two values of any type with operator<int, double, std::string, anything comparable. No overload per type, no std::max.

Constraints

  • Must be a function template (template <typename T>)
  • Works for any type providing operator< (tests use int, double, std::string)
  • Do not call std::max — implement the comparison yourself
  • For equal arguments, returning either is fine

Before you code

  • What does the compiler actually generate when you call maxOf(2, 7) and maxOf(a, b) with strings?
  • Why take the parameters by const T& rather than by value?
  • What happens at compile time if T has no operator<?

Tests

  • #1Works for int
  • #2Works for double
  • #3Works for std::string

Hints

Hint 1

The body is one line: return (a < b) ? b : a; — only operator< is required of T.

Editortype-safe-max.cpp
Results

Hit Submit (or ⌘/Ctrl + ↵) — test results will show up here.