3 Defines `boost::hana::capture`.
5 @copyright Louis Dionne 2013-2017
6 Distributed under the Boost Software License, Version 1.0.
7 (See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)
10 #ifndef BOOST_HANA_FUNCTIONAL_CAPTURE_HPP
11 #define BOOST_HANA_FUNCTIONAL_CAPTURE_HPP
13 #include <boost/hana/basic_tuple.hpp>
14 #include <boost/hana/config.hpp>
15 #include <boost/hana/detail/decay.hpp>
16 #include <boost/hana/functional/partial.hpp>
22 BOOST_HANA_NAMESPACE_BEGIN
23 //! @ingroup group-functional
24 //! Create a function capturing the given variables.
26 //! Given 0 or more variables, `capture` creates a closure that can be
27 //! used to partially apply a function. This is very similar to `partial`,
28 //! except that `capture` allows the partially applied function to be
29 //! specified later. Specifically, `capture(vars...)` is a function object
30 //! taking a function `f` and returning `f` partially applied to `vars...`.
33 //! capture(vars...)(f)(args...) == f(vars..., args...)
37 //! The arity of `f` must match the total number of arguments passed to
38 //! it, i.e. `sizeof...(vars) + sizeof...(args)`.
43 //! @include example/functional/capture.cpp
44 #ifdef BOOST_HANA_DOXYGEN_INVOKED
45 constexpr auto capture = [](auto&& ...variables) {
46 return [perfect-capture](auto&& f) {
47 return [perfect-capture](auto&& ...args) -> decltype(auto) {
48 return forwarded(f)(forwarded(variables)..., forwarded(args)...);
54 template <typename F, typename Closure, std::size_t ...i>
55 constexpr auto apply_capture(F&& f, Closure&& closure, std::index_sequence<i...>) {
56 return hana::partial(static_cast<F&&>(f),
57 hana::at_c<i>(static_cast<Closure&&>(closure).storage_)...
62 template <typename ...X>
65 struct make_capture_t {
67 template <typename ...X>
68 constexpr capture_t<typename detail::decay<X>::type...>
69 operator()(X&& ...x) const {
70 return {secret{}, static_cast<X&&>(x)...};
74 template <typename ...X>
76 template <typename ...Y>
77 constexpr capture_t(make_capture_t::secret, Y&& ...y)
78 : storage_{static_cast<Y&&>(y)...}
81 basic_tuple<X...> storage_;
84 constexpr auto operator()(F&& f) const& {
85 return detail::apply_capture(
86 static_cast<F&&>(f), *this,
87 std::make_index_sequence<sizeof...(X)>{}
92 constexpr auto operator()(F&& f) & {
93 return detail::apply_capture(
94 static_cast<F&&>(f), *this,
95 std::make_index_sequence<sizeof...(X)>{}
100 constexpr auto operator()(F&& f) && {
101 return detail::apply_capture(
102 static_cast<F&&>(f), static_cast<capture_t&&>(*this),
103 std::make_index_sequence<sizeof...(X)>{}
108 constexpr make_capture_t capture{};
110 BOOST_HANA_NAMESPACE_END
112 #endif // !BOOST_HANA_FUNCTIONAL_CAPTURE_HPP