xref: /aosp_15_r20/external/abseil-cpp/absl/functional/bind_front.h (revision 9356374a3709195abf420251b3e825997ff56c0f)
1 // Copyright 2018 The Abseil Authors.
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 //      https://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14 //
15 // -----------------------------------------------------------------------------
16 // File: bind_front.h
17 // -----------------------------------------------------------------------------
18 //
19 // `absl::bind_front()` returns a functor by binding a number of arguments to
20 // the front of a provided (usually more generic) functor. Unlike `std::bind`,
21 // it does not require the use of argument placeholders. The simpler syntax of
22 // `absl::bind_front()` allows you to avoid known misuses with `std::bind()`.
23 //
24 // `absl::bind_front()` is meant as a drop-in replacement for C++20's upcoming
25 // `std::bind_front()`, which similarly resolves these issues with
26 // `std::bind()`. Both `bind_front()` alternatives, unlike `std::bind()`, allow
27 // partial function application. (See
28 // https://en.wikipedia.org/wiki/Partial_application).
29 
30 #ifndef ABSL_FUNCTIONAL_BIND_FRONT_H_
31 #define ABSL_FUNCTIONAL_BIND_FRONT_H_
32 
33 #if defined(__cpp_lib_bind_front) && __cpp_lib_bind_front >= 201907L
34 #include <functional>  // For std::bind_front.
35 #endif  // defined(__cpp_lib_bind_front) && __cpp_lib_bind_front >= 201907L
36 
37 #include <utility>
38 
39 #include "absl/functional/internal/front_binder.h"
40 #include "absl/utility/utility.h"
41 
42 namespace absl {
43 ABSL_NAMESPACE_BEGIN
44 
45 // bind_front()
46 //
47 // Binds the first N arguments of an invocable object and stores them by value.
48 //
49 // Like `std::bind()`, `absl::bind_front()` is implicitly convertible to
50 // `std::function`.  In particular, it may be used as a simpler replacement for
51 // `std::bind()` in most cases, as it does not require placeholders to be
52 // specified. More importantly, it provides more reliable correctness guarantees
53 // than `std::bind()`; while `std::bind()` will silently ignore passing more
54 // parameters than expected, for example, `absl::bind_front()` will report such
55 // mis-uses as errors. In C++20, `absl::bind_front` is replaced by
56 // `std::bind_front`.
57 //
58 // absl::bind_front(a...) can be seen as storing the results of
59 // std::make_tuple(a...).
60 //
61 // Example: Binding a free function.
62 //
63 //   int Minus(int a, int b) { return a - b; }
64 //
65 //   assert(absl::bind_front(Minus)(3, 2) == 3 - 2);
66 //   assert(absl::bind_front(Minus, 3)(2) == 3 - 2);
67 //   assert(absl::bind_front(Minus, 3, 2)() == 3 - 2);
68 //
69 // Example: Binding a member function.
70 //
71 //   struct Math {
72 //     int Double(int a) const { return 2 * a; }
73 //   };
74 //
75 //   Math math;
76 //
77 //   assert(absl::bind_front(&Math::Double)(&math, 3) == 2 * 3);
78 //   // Stores a pointer to math inside the functor.
79 //   assert(absl::bind_front(&Math::Double, &math)(3) == 2 * 3);
80 //   // Stores a copy of math inside the functor.
81 //   assert(absl::bind_front(&Math::Double, math)(3) == 2 * 3);
82 //   // Stores std::unique_ptr<Math> inside the functor.
83 //   assert(absl::bind_front(&Math::Double,
84 //                           std::unique_ptr<Math>(new Math))(3) == 2 * 3);
85 //
86 // Example: Using `absl::bind_front()`, instead of `std::bind()`, with
87 //          `std::function`.
88 //
89 //   class FileReader {
90 //    public:
91 //     void ReadFileAsync(const std::string& filename, std::string* content,
92 //                        const std::function<void()>& done) {
93 //       // Calls Executor::Schedule(std::function<void()>).
94 //       Executor::DefaultExecutor()->Schedule(
95 //           absl::bind_front(&FileReader::BlockingRead, this,
96 //                            filename, content, done));
97 //     }
98 //
99 //    private:
100 //     void BlockingRead(const std::string& filename, std::string* content,
101 //                       const std::function<void()>& done) {
102 //       CHECK_OK(file::GetContents(filename, content, {}));
103 //       done();
104 //     }
105 //   };
106 //
107 // `absl::bind_front()` stores bound arguments explicitly using the type passed
108 // rather than implicitly based on the type accepted by its functor.
109 //
110 // Example: Binding arguments explicitly.
111 //
112 //   void LogStringView(absl::string_view sv) {
113 //     LOG(INFO) << sv;
114 //   }
115 //
116 //   Executor* e = Executor::DefaultExecutor();
117 //   std::string s = "hello";
118 //   absl::string_view sv = s;
119 //
120 //   // absl::bind_front(LogStringView, arg) makes a copy of arg and stores it.
121 //   e->Schedule(absl::bind_front(LogStringView, sv)); // ERROR: dangling
122 //                                                     // string_view.
123 //
124 //   e->Schedule(absl::bind_front(LogStringView, s));  // OK: stores a copy of
125 //                                                     // s.
126 //
127 // To store some of the arguments passed to `absl::bind_front()` by reference,
128 //  use std::ref()` and `std::cref()`.
129 //
130 // Example: Storing some of the bound arguments by reference.
131 //
132 //   class Service {
133 //    public:
134 //     void Serve(const Request& req, std::function<void()>* done) {
135 //       // The request protocol buffer won't be deleted until done is called.
136 //       // It's safe to store a reference to it inside the functor.
137 //       Executor::DefaultExecutor()->Schedule(
138 //           absl::bind_front(&Service::BlockingServe, this, std::cref(req),
139 //           done));
140 //     }
141 //
142 //    private:
143 //     void BlockingServe(const Request& req, std::function<void()>* done);
144 //   };
145 //
146 // Example: Storing bound arguments by reference.
147 //
148 //   void Print(const std::string& a, const std::string& b) {
149 //     std::cerr << a << b;
150 //   }
151 //
152 //   std::string hi = "Hello, ";
153 //   std::vector<std::string> names = {"Chuk", "Gek"};
154 //   // Doesn't copy hi.
155 //   for_each(names.begin(), names.end(),
156 //            absl::bind_front(Print, std::ref(hi)));
157 //
158 //   // DO NOT DO THIS: the functor may outlive "hi", resulting in
159 //   // dangling references.
160 //   foo->DoInFuture(absl::bind_front(Print, std::ref(hi), "Guest"));  // BAD!
161 //   auto f = absl::bind_front(Print, std::ref(hi), "Guest"); // BAD!
162 //
163 // Example: Storing reference-like types.
164 //
165 //   void Print(absl::string_view a, const std::string& b) {
166 //     std::cerr << a << b;
167 //   }
168 //
169 //   std::string hi = "Hello, ";
170 //   // Copies "hi".
171 //   absl::bind_front(Print, hi)("Chuk");
172 //
173 //   // Compile error: std::reference_wrapper<const string> is not implicitly
174 //   // convertible to string_view.
175 //   // absl::bind_front(Print, std::cref(hi))("Chuk");
176 //
177 //   // Doesn't copy "hi".
178 //   absl::bind_front(Print, absl::string_view(hi))("Chuk");
179 //
180 #if defined(__cpp_lib_bind_front) && __cpp_lib_bind_front >= 201907L
181 using std::bind_front;
182 #else   // defined(__cpp_lib_bind_front) && __cpp_lib_bind_front >= 201907L
183 template <class F, class... BoundArgs>
184 constexpr functional_internal::bind_front_t<F, BoundArgs...> bind_front(
185     F&& func, BoundArgs&&... args) {
186   return functional_internal::bind_front_t<F, BoundArgs...>(
187       absl::in_place, std::forward<F>(func), std::forward<BoundArgs>(args)...);
188 }
189 #endif  // defined(__cpp_lib_bind_front) && __cpp_lib_bind_front >= 201907L
190 
191 ABSL_NAMESPACE_END
192 }  // namespace absl
193 
194 #endif  // ABSL_FUNCTIONAL_BIND_FRONT_H_
195