cxx17_backports.h 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. // Copyright 2021 The Chromium Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style license that can be
  3. // found in the LICENSE file.
  4. #ifndef BASE_CXX17_BACKPORTS_H_
  5. #define BASE_CXX17_BACKPORTS_H_
  6. #include <functional>
  7. #include <tuple>
  8. #include <type_traits>
  9. #include <utility>
  10. #include "base/check.h"
  11. #include "base/functional/invoke.h"
  12. namespace base {
  13. // C++14 implementation of C++17's std::clamp():
  14. // https://en.cppreference.com/w/cpp/algorithm/clamp
  15. // Please note that the C++ spec makes it undefined behavior to call std::clamp
  16. // with a value of `lo` that compares greater than the value of `hi`. This
  17. // implementation uses a CHECK to enforce this as a hard restriction.
  18. template <typename T, typename Compare>
  19. constexpr const T& clamp(const T& v, const T& lo, const T& hi, Compare comp) {
  20. CHECK(!comp(hi, lo));
  21. return comp(v, lo) ? lo : comp(hi, v) ? hi : v;
  22. }
  23. template <typename T>
  24. constexpr const T& clamp(const T& v, const T& lo, const T& hi) {
  25. return base::clamp(v, lo, hi, std::less<T>{});
  26. }
  27. // C++14 implementation of C++17's std::apply():
  28. // https://en.cppreference.com/w/cpp/utility/apply
  29. namespace internal {
  30. template <class F, class Tuple, std::size_t... I>
  31. constexpr decltype(auto) apply_impl(F&& f,
  32. Tuple&& t,
  33. std::index_sequence<I...>) {
  34. return base::invoke(std::forward<F>(f),
  35. std::get<I>(std::forward<Tuple>(t))...);
  36. }
  37. } // namespace internal
  38. template <class F, class Tuple>
  39. constexpr decltype(auto) apply(F&& f, Tuple&& t) {
  40. return internal::apply_impl(
  41. std::forward<F>(f), std::forward<Tuple>(t),
  42. std::make_index_sequence<
  43. std::tuple_size<std::remove_reference_t<Tuple>>::value>{});
  44. }
  45. } // namespace base
  46. #endif // BASE_CXX17_BACKPORTS_H_