Minimum and Maximum Algorithms

clamp() with custom types

How can I use clamp() with custom types?

Abstract art representing computer programming

To use std::ranges::clamp() with custom types, you need to define the appropriate comparison operators for your type. The spaceship operator (<=>) provides a concise way to implement all the necessary comparison operators.

Step 1: Define the Custom Type

First, create your custom type and manually implement the spaceship operator (<=>). This will automatically provide the required comparison operators.

#include <algorithm>
#include <iostream>
#include <compare>

struct Player {
  int Health;

  // Spaceship operator for three-way comparison
  std::strong_ordering operator<=>(const Player& other) const {
    return Health <=> other.Health;

  // Equality operator
  bool operator==(const Player& other) const {
    return Health == other.Health;

Step 2: Use std::ranges::clamp()

With the comparison operators defined, you can now use std::ranges::clamp() with instances of your custom type:

#include <algorithm>
#include <iostream>

struct Player {/*...*/}; int main() { Player p1{50}; Player p2{100}; Player p3{150}; Player clampedPlayer = std::ranges::clamp(p2, p1, p3); std::cout << "Clamped Player Health: " << clampedPlayer.Health; }
Clamped Player Health: 100

In this example, std::ranges::clamp() ensures that the Health of p2 stays within the bounds set by p1 and p3. Since p2's Health is already within the range, it remains unchanged.


  • Define the Spaceship Operator: The Player struct has the <=> operator defined, which compares Health values using std::strong_ordering. This operator provides functionality for determining the relative ordering of Player objects.
  • Define the Equality Operator: The equality operator (==) is explicitly defined to determine whether two Player objects are equal, by comparing their Health values.
  • Use std::ranges::clamp(): The std::ranges::clamp() function ensures that p2's Health is clamped between p1's and p3's Health.

By implementing the necessary comparison operators, you enable std::ranges::clamp() to work with your custom types, making your code more flexible and powerful.

Answers to questions are automatically generated and may not have been reviewed.

A computer programmer
Part of the course:

Professional C++

Comprehensive course covering advanced concepts, and how to use them on large-scale projects.

Free, unlimited access

This course includes:

  • 124 Lessons
  • 550+ Code Samples
  • 96% Positive Reviews
  • Regularly Updated
  • Help and FAQ
Free, Unlimited Access

Professional C++

Comprehensive course covering advanced concepts, and how to use them on large-scale projects.

Screenshot from Warhammer: Total War
Screenshot from Tomb Raider
Screenshot from Jedi: Fallen Order
Contact|Privacy Policy|Terms of Use
Copyright © 2024 - All Rights Reserved