functional.h 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. // Copyright 2020 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_UTIL_RANGES_FUNCTIONAL_H_
  5. #define BASE_UTIL_RANGES_FUNCTIONAL_H_
  6. #include <functional>
  7. #include <type_traits>
  8. #include <utility>
  9. namespace util {
  10. // Implementation of C++20's std::identity.
  11. //
  12. // Reference:
  13. // - https://en.cppreference.com/w/cpp/utility/functional/identity
  14. // - https://wg21.link/func.identity
  15. struct identity {
  16. template <typename T>
  17. constexpr T&& operator()(T&& t) const noexcept {
  18. return std::forward<T>(t);
  19. }
  20. using is_transparent = void;
  21. };
  22. // Minimal implementation of C++17's std::invoke. Based on implementation
  23. // referenced in original std::invoke proposal.
  24. //
  25. // Note: Unlike C++20's std::invoke this implementation is not constexpr. A
  26. // constexpr version can be added in the future, but it won't be as concise,
  27. // since std::mem_fn is not constexpr prior to C++20.
  28. //
  29. // References:
  30. // - https://wg21.link/n4169#implementability
  31. // - https://en.cppreference.com/w/cpp/utility/functional/invoke
  32. // - https://wg21.link/func.invoke
  33. template <typename Functor,
  34. typename... Args,
  35. std::enable_if_t<
  36. std::is_member_pointer<std::decay_t<Functor>>::value>* = nullptr>
  37. decltype(auto) invoke(Functor&& f, Args&&... args) {
  38. return std::mem_fn(f)(std::forward<Args>(args)...);
  39. }
  40. template <typename Functor,
  41. typename... Args,
  42. std::enable_if_t<
  43. !std::is_member_pointer<std::decay_t<Functor>>::value>* = nullptr>
  44. decltype(auto) invoke(Functor&& f, Args&&... args) {
  45. return std::forward<Functor>(f)(std::forward<Args>(args)...);
  46. }
  47. // Simplified implementations of C++20's std::ranges comparison function
  48. // objects. As opposed to the std::ranges implementation, these versions do not
  49. // constrain the passed-in types.
  50. //
  51. // Reference: https://wg21.link/range.cmp
  52. namespace ranges {
  53. using equal_to = std::equal_to<>;
  54. using less = std::less<>;
  55. } // namespace ranges
  56. } // namespace util
  57. #endif // BASE_UTIL_RANGES_FUNCTIONAL_H_