tap.hpp 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. /*=============================================================================
  2. Copyright (c) 2014 Paul Fultz II
  3. tap.h
  4. Distributed under the Boost Software License, Version 1.0. (See accompanying
  5. file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
  6. ==============================================================================*/
  7. #ifndef BOOST_HOF_GUARD_FUNCTION_TAP_H
  8. #define BOOST_HOF_GUARD_FUNCTION_TAP_H
  9. /// tap
  10. /// ===
  11. ///
  12. /// Description
  13. /// -----------
  14. ///
  15. /// The `tap` function invokes a function on the first argument passed in and
  16. /// then returns the first argument. This is useful in a chain of pipable
  17. /// function to perform operations on intermediate results. As a result, this
  18. /// function is [`pipable`](/include/boost/hof/pipable).
  19. ///
  20. /// Synopsis
  21. /// --------
  22. ///
  23. /// template<class T, class F>
  24. /// pipable constexpr T tap(T&& x, const F& f);
  25. ///
  26. /// Requirements
  27. /// ------------
  28. ///
  29. /// F must be:
  30. ///
  31. /// * [UnaryInvocable](UnaryInvocable)
  32. ///
  33. /// Example
  34. /// -------
  35. ///
  36. /// #include <boost/hof.hpp>
  37. /// #include <cassert>
  38. /// #include <iostream>
  39. /// using namespace boost::hof;
  40. ///
  41. /// struct sum_f
  42. /// {
  43. /// template<class T, class U>
  44. /// T operator()(T x, U y) const
  45. /// {
  46. /// return x+y;
  47. /// }
  48. /// };
  49. ///
  50. /// const pipable_adaptor<sum_f> sum = {};
  51. /// int main() {
  52. /// // Prints 3
  53. /// int r = 1 | sum(2) | tap([](int i) { std::cout << i; }) | sum(2);
  54. /// assert(r == 5);
  55. /// }
  56. ///
  57. #include <boost/hof/pipable.hpp>
  58. #include <boost/hof/apply.hpp>
  59. #include <boost/hof/detail/static_const_var.hpp>
  60. namespace boost { namespace hof { namespace detail {
  61. struct tap_f
  62. {
  63. template<class T, class F>
  64. constexpr T operator()(T&& x, const F& f) const
  65. BOOST_HOF_RETURNS_DEDUCE_NOEXCEPT((boost::hof::apply(f, x), BOOST_HOF_FORWARD(T)(x)))
  66. {
  67. return boost::hof::apply(f, x), BOOST_HOF_FORWARD(T)(x);
  68. }
  69. };
  70. }
  71. BOOST_HOF_DECLARE_STATIC_VAR(tap, pipable_adaptor<detail::tap_f>);
  72. }} // namespace boost::hof
  73. #endif