1 // Copyright 2021 The Chromium Authors
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #ifndef BASE_CXX17_BACKPORTS_H_
6 #define BASE_CXX17_BACKPORTS_H_
10 #include "base/check.h"
14 // C++14 implementation of C++17's std::clamp():
15 // https://en.cppreference.com/w/cpp/algorithm/clamp
16 // Please note that the C++ spec makes it undefined behavior to call std::clamp
17 // with a value of `lo` that compares greater than the value of `hi`. This
18 // implementation uses a CHECK to enforce this as a hard restriction.
19 template <typename T, typename Compare>
20 constexpr const T& clamp(const T& v, const T& lo, const T& hi, Compare comp) {
22 return comp(v, lo) ? lo : comp(hi, v) ? hi : v;
26 constexpr const T& clamp(const T& v, const T& lo, const T& hi) {
27 return base::clamp(v, lo, hi, std::less<T>{});
32 #endif // BASE_CXX17_BACKPORTS_H_