1 // Copyright (c) 2012 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 // NOTE: Header files that do not require the full definition of
6 // base::{Once,Repeating}Callback or base::{Once,Repeating}Closure should
7 // #include "base/callback_forward.h" instead of this file.
9 #ifndef BASE_CALLBACK_H_
10 #define BASE_CALLBACK_H_
14 #include "base/bind.h"
15 #include "base/callback_forward.h"
16 #include "base/callback_internal.h"
17 #include "base/notreached.h"
19 // -----------------------------------------------------------------------------
20 // Usage documentation
21 // -----------------------------------------------------------------------------
24 // A callback is similar in concept to a function pointer: it wraps a runnable
25 // object such as a function, method, lambda, or even another callback, allowing
26 // the runnable object to be invoked later via the callback object.
28 // Unlike function pointers, callbacks are created with base::BindOnce() or
29 // base::BindRepeating() and support partial function application.
31 // A base::OnceCallback may be Run() at most once; a base::RepeatingCallback may
32 // be Run() any number of times. |is_null()| is guaranteed to return true for a
33 // moved-from callback.
35 // // The lambda takes two arguments, but the first argument |x| is bound at
36 // // callback creation.
37 // base::OnceCallback<int(int)> cb = base::BindOnce([] (int x, int y) {
40 // // Run() only needs the remaining unbound argument |y|.
41 // printf("1 + 2 = %d\n", std::move(cb).Run(2)); // Prints 3
42 // printf("cb is null? %s\n",
43 // cb.is_null() ? "true" : "false"); // Prints true
44 // std::move(cb).Run(2); // Crashes since |cb| has already run.
46 // Callbacks also support cancellation. A common use is binding the receiver
47 // object as a WeakPtr<T>. If that weak pointer is invalidated, calling Run()
48 // will be a no-op. Note that |IsCancelled()| and |is_null()| are distinct:
49 // simply cancelling a callback will not also make it null.
51 // See //docs/callback.md for the full documentation.
55 template <typename R, typename... Args>
56 class OnceCallback<R(Args...)> : public internal::CallbackBase {
59 using RunType = R(Args...);
60 using PolymorphicInvoke = R (*)(internal::BindStateBase*,
61 internal::PassingType<Args>...);
63 constexpr OnceCallback() = default;
64 OnceCallback(std::nullptr_t) = delete;
66 explicit OnceCallback(internal::BindStateBase* bind_state)
67 : internal::CallbackBase(bind_state) {}
69 OnceCallback(const OnceCallback&) = delete;
70 OnceCallback& operator=(const OnceCallback&) = delete;
72 OnceCallback(OnceCallback&&) noexcept = default;
73 OnceCallback& operator=(OnceCallback&&) noexcept = default;
75 OnceCallback(RepeatingCallback<RunType> other)
76 : internal::CallbackBase(std::move(other)) {}
78 OnceCallback& operator=(RepeatingCallback<RunType> other) {
79 static_cast<internal::CallbackBase&>(*this) = std::move(other);
83 R Run(Args... args) const & {
84 static_assert(!sizeof(*this),
85 "OnceCallback::Run() may only be invoked on a non-const "
86 "rvalue, i.e. std::move(callback).Run().");
90 R Run(Args... args) && {
91 // Move the callback instance into a local variable before the invocation,
92 // that ensures the internal state is cleared after the invocation.
93 // It's not safe to touch |this| after the invocation, since running the
94 // bound function may destroy |this|.
95 OnceCallback cb = std::move(*this);
97 reinterpret_cast<PolymorphicInvoke>(cb.polymorphic_invoke());
98 return f(cb.bind_state_.get(), std::forward<Args>(args)...);
101 // Then() returns a new OnceCallback that receives the same arguments as
102 // |this|, and with the return type of |then|. The returned callback will:
103 // 1) Run the functor currently bound to |this| callback.
104 // 2) Run the |then| callback with the result from step 1 as its single
106 // 3) Return the value from running the |then| callback.
108 // Since this method generates a callback that is a replacement for `this`,
109 // `this` will be consumed and reset to a null callback to ensure the
110 // originally-bound functor can be run at most once.
111 template <typename ThenR, typename... ThenArgs>
112 OnceCallback<ThenR(Args...)> Then(OnceCallback<ThenR(ThenArgs...)> then) && {
115 internal::ThenHelper<
116 OnceCallback, OnceCallback<ThenR(ThenArgs...)>>::CreateTrampoline(),
117 std::move(*this), std::move(then));
120 // This overload is required; even though RepeatingCallback is implicitly
121 // convertible to OnceCallback, that conversion will not used when matching
122 // for template argument deduction.
123 template <typename ThenR, typename... ThenArgs>
124 OnceCallback<ThenR(Args...)> Then(
125 RepeatingCallback<ThenR(ThenArgs...)> then) && {
128 internal::ThenHelper<
130 RepeatingCallback<ThenR(ThenArgs...)>>::CreateTrampoline(),
131 std::move(*this), std::move(then));
135 template <typename R, typename... Args>
136 class RepeatingCallback<R(Args...)> : public internal::CallbackBaseCopyable {
138 using ResultType = R;
139 using RunType = R(Args...);
140 using PolymorphicInvoke = R (*)(internal::BindStateBase*,
141 internal::PassingType<Args>...);
143 constexpr RepeatingCallback() = default;
144 RepeatingCallback(std::nullptr_t) = delete;
146 explicit RepeatingCallback(internal::BindStateBase* bind_state)
147 : internal::CallbackBaseCopyable(bind_state) {}
149 // Copyable and movable.
150 RepeatingCallback(const RepeatingCallback&) = default;
151 RepeatingCallback& operator=(const RepeatingCallback&) = default;
152 RepeatingCallback(RepeatingCallback&&) noexcept = default;
153 RepeatingCallback& operator=(RepeatingCallback&&) noexcept = default;
155 bool operator==(const RepeatingCallback& other) const {
156 return EqualsInternal(other);
159 bool operator!=(const RepeatingCallback& other) const {
160 return !operator==(other);
163 R Run(Args... args) const & {
164 PolymorphicInvoke f =
165 reinterpret_cast<PolymorphicInvoke>(this->polymorphic_invoke());
166 return f(this->bind_state_.get(), std::forward<Args>(args)...);
169 R Run(Args... args) && {
170 // Move the callback instance into a local variable before the invocation,
171 // that ensures the internal state is cleared after the invocation.
172 // It's not safe to touch |this| after the invocation, since running the
173 // bound function may destroy |this|.
174 RepeatingCallback cb = std::move(*this);
175 PolymorphicInvoke f =
176 reinterpret_cast<PolymorphicInvoke>(cb.polymorphic_invoke());
177 return f(std::move(cb).bind_state_.get(), std::forward<Args>(args)...);
180 // Then() returns a new RepeatingCallback that receives the same arguments as
181 // |this|, and with the return type of |then|. The
182 // returned callback will:
183 // 1) Run the functor currently bound to |this| callback.
184 // 2) Run the |then| callback with the result from step 1 as its single
186 // 3) Return the value from running the |then| callback.
188 // If called on an rvalue (e.g. std::move(cb).Then(...)), this method
189 // generates a callback that is a replacement for `this`. Therefore, `this`
190 // will be consumed and reset to a null callback to ensure the
191 // originally-bound functor will be run at most once.
192 template <typename ThenR, typename... ThenArgs>
193 RepeatingCallback<ThenR(Args...)> Then(
194 RepeatingCallback<ThenR(ThenArgs...)> then) const& {
196 return BindRepeating(
197 internal::ThenHelper<
199 RepeatingCallback<ThenR(ThenArgs...)>>::CreateTrampoline(),
200 *this, std::move(then));
203 template <typename ThenR, typename... ThenArgs>
204 RepeatingCallback<ThenR(Args...)> Then(
205 RepeatingCallback<ThenR(ThenArgs...)> then) && {
207 return BindRepeating(
208 internal::ThenHelper<
210 RepeatingCallback<ThenR(ThenArgs...)>>::CreateTrampoline(),
211 std::move(*this), std::move(then));
217 #endif // BASE_CALLBACK_H_