flip.hpp 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. /*!
  2. @file
  3. Defines `boost::hana::flip`.
  4. @copyright Louis Dionne 2013-2017
  5. Distributed under the Boost Software License, Version 1.0.
  6. (See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)
  7. */
  8. #ifndef BOOST_HANA_FUNCTIONAL_FLIP_HPP
  9. #define BOOST_HANA_FUNCTIONAL_FLIP_HPP
  10. #include <boost/hana/config.hpp>
  11. #include <boost/hana/detail/create.hpp>
  12. #include <utility>
  13. BOOST_HANA_NAMESPACE_BEGIN
  14. //! @ingroup group-functional
  15. //! Invoke a function with its two first arguments reversed.
  16. //!
  17. //! Specifically, `flip(f)` is a function such that
  18. //! @code
  19. //! flip(f)(x, y, z...) == f(y, x, z...)
  20. //! @endcode
  21. //!
  22. //! ### Example
  23. //! @include example/functional/flip.cpp
  24. #ifdef BOOST_HANA_DOXYGEN_INVOKED
  25. constexpr auto flip = [](auto&& f) {
  26. return [perfect-capture](auto&& x, auto&& y, auto&& ...z) -> decltype(auto) {
  27. return forwarded(f)(forwarded(y), forwarded(x), forwarded(z)...);
  28. };
  29. };
  30. #else
  31. template <typename F>
  32. struct flip_t {
  33. F f;
  34. template <typename X, typename Y, typename ...Z>
  35. constexpr decltype(auto) operator()(X&& x, Y&& y, Z&& ...z) const& {
  36. return f(
  37. static_cast<Y&&>(y),
  38. static_cast<X&&>(x),
  39. static_cast<Z&&>(z)...
  40. );
  41. }
  42. template <typename X, typename Y, typename ...Z>
  43. constexpr decltype(auto) operator()(X&& x, Y&& y, Z&& ...z) & {
  44. return f(
  45. static_cast<Y&&>(y),
  46. static_cast<X&&>(x),
  47. static_cast<Z&&>(z)...
  48. );
  49. }
  50. template <typename X, typename Y, typename ...Z>
  51. constexpr decltype(auto) operator()(X&& x, Y&& y, Z&& ...z) && {
  52. return std::move(f)(
  53. static_cast<Y&&>(y),
  54. static_cast<X&&>(x),
  55. static_cast<Z&&>(z)...
  56. );
  57. }
  58. };
  59. constexpr detail::create<flip_t> flip{};
  60. #endif
  61. BOOST_HANA_NAMESPACE_END
  62. #endif // !BOOST_HANA_FUNCTIONAL_FLIP_HPP