Write a generic maximum template

Description: Write a function template max_of which returns the bigger of two values. Use it with int, double and std::string. Then limit it to types which can be compared with a concept.

Hint:

  • std::totally_ordered is a ready concept for comparable types.

Solution

#include <concepts>
#include <iostream>
#include <string>

template <std::totally_ordered T>
T max_of(T a, T b) {
    return a > b ? a : b;
}

int main() {
    std::cout << max_of(3, 9) << '\n';
    std::cout << max_of(2.5, 1.5) << '\n';
    std::cout << max_of(std::string("pear"), std::string("apple")) << '\n';
}
Output

9
2.5
pear

How it works

  • The compiler makes one version of the function for each type you use.
  • The concept gives a clear error when the type can not be compared.

Read C++ Templates.


Learn more about the similar topics:
Tutorials
No Content Found.
Exercises & Assignments
No Content Found.
Interview Questions & Answers
No Content Found.