You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

overload.hpp 2.4KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. /// \file
  2. // Range v3 library
  3. //
  4. // Copyright Eric Niebler 2013-present
  5. //
  6. // Use, modification and distribution is subject to the
  7. // Boost Software License, Version 1.0. (See accompanying
  8. // file LICENSE_1_0.txt or copy at
  9. // http://www.boost.org/LICENSE_1_0.txt)
  10. //
  11. // Project home: https://github.com/ericniebler/range-v3
  12. //
  13. #ifndef RANGES_V3_FUNCTIONAL_OVERLOAD_HPP
  14. #define RANGES_V3_FUNCTIONAL_OVERLOAD_HPP
  15. #include <concepts/concepts.hpp>
  16. #include <range/v3/range_fwd.hpp>
  17. #include <range/v3/functional/invoke.hpp>
  18. #include <range/v3/utility/static_const.hpp>
  19. namespace ranges
  20. {
  21. /// \addtogroup group-functional
  22. /// @{
  23. template<typename... Ts>
  24. struct overloaded;
  25. template<>
  26. struct overloaded<>
  27. {};
  28. template<typename First, typename... Rest>
  29. struct overloaded<First, Rest...>
  30. {
  31. private:
  32. RANGES_NO_UNIQUE_ADDRESS
  33. First first_;
  34. RANGES_NO_UNIQUE_ADDRESS
  35. overloaded<Rest...> second_;
  36. public:
  37. overloaded() = default;
  38. constexpr overloaded(First first, Rest... rest)
  39. : first_(static_cast<First &&>(first))
  40. , second_{static_cast<Rest &&>(rest)...}
  41. {}
  42. // clang-format off
  43. template<typename... Args>
  44. auto CPP_auto_fun(operator())(Args &&...args)
  45. (
  46. return invoke(first_, static_cast<Args &&>(args)...)
  47. )
  48. template<typename... Args>
  49. auto CPP_auto_fun(operator())(Args &&...args) (const)
  50. (
  51. return invoke((First const &) first_, static_cast<Args &&>(args)...)
  52. )
  53. template<typename... Args>
  54. auto CPP_auto_fun(operator())(Args &&...args)
  55. (
  56. return second_(static_cast<Args &&>(args)...)
  57. )
  58. template<typename... Args>
  59. auto CPP_auto_fun(operator())(Args &&...args) (const)
  60. (
  61. return ((overloaded<Rest...> const &) second_)(static_cast<Args &&>(args)...)
  62. )
  63. // clang-format on
  64. };
  65. struct overload_fn
  66. {
  67. template<typename Fn>
  68. constexpr Fn operator()(Fn fn) const
  69. {
  70. return fn;
  71. }
  72. template<typename... Fns>
  73. constexpr overloaded<Fns...> operator()(Fns... fns) const
  74. {
  75. return overloaded<Fns...>{static_cast<Fns &&>(fns)...};
  76. }
  77. };
  78. /// \ingroup group-functional
  79. /// \sa `overload_fn`
  80. RANGES_INLINE_VARIABLE(overload_fn, overload)
  81. /// @}
  82. } // namespace ranges
  83. #endif