callback.h 5.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150
  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.
  4. //
  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.
  8. #ifndef BASE_CALLBACK_H_
  9. #define BASE_CALLBACK_H_
  10. #include <stddef.h>
  11. #include "base/callback_forward.h"
  12. #include "base/callback_internal.h"
  13. #include "base/logging.h"
  14. // -----------------------------------------------------------------------------
  15. // Usage documentation
  16. // -----------------------------------------------------------------------------
  17. //
  18. // Overview:
  19. // A callback is similar in concept to a function pointer: it wraps a runnable
  20. // object such as a function, method, lambda, or even another callback, allowing
  21. // the runnable object to be invoked later via the callback object.
  22. //
  23. // Unlike function pointers, callbacks are created with base::BindOnce() or
  24. // base::BindRepeating() and support partial function application.
  25. //
  26. // A base::OnceCallback may be Run() at most once; a base::RepeatingCallback may
  27. // be Run() any number of times. |is_null()| is guaranteed to return true for a
  28. // moved-from callback.
  29. //
  30. // // The lambda takes two arguments, but the first argument |x| is bound at
  31. // // callback creation.
  32. // base::OnceCallback<int(int)> cb = base::BindOnce([] (int x, int y) {
  33. // return x + y;
  34. // }, 1);
  35. // // Run() only needs the remaining unbound argument |y|.
  36. // printf("1 + 2 = %d\n", std::move(cb).Run(2)); // Prints 3
  37. // printf("cb is null? %s\n",
  38. // cb.is_null() ? "true" : "false"); // Prints true
  39. // std::move(cb).Run(2); // Crashes since |cb| has already run.
  40. //
  41. // Callbacks also support cancellation. A common use is binding the receiver
  42. // object as a WeakPtr<T>. If that weak pointer is invalidated, calling Run()
  43. // will be a no-op. Note that |IsCancelled()| and |is_null()| are distinct:
  44. // simply cancelling a callback will not also make it null.
  45. //
  46. // base::Callback is currently a type alias for base::RepeatingCallback. In the
  47. // future, we expect to flip this to default to base::OnceCallback.
  48. //
  49. // See //docs/callback.md for the full documentation.
  50. namespace base {
  51. template <typename R, typename... Args>
  52. class OnceCallback<R(Args...)> : public internal::CallbackBase {
  53. public:
  54. using RunType = R(Args...);
  55. using PolymorphicInvoke = R (*)(internal::BindStateBase*,
  56. internal::PassingType<Args>...);
  57. constexpr OnceCallback() = default;
  58. OnceCallback(std::nullptr_t) = delete;
  59. explicit OnceCallback(internal::BindStateBase* bind_state)
  60. : internal::CallbackBase(bind_state) {}
  61. OnceCallback(const OnceCallback&) = delete;
  62. OnceCallback& operator=(const OnceCallback&) = delete;
  63. OnceCallback(OnceCallback&&) noexcept = default;
  64. OnceCallback& operator=(OnceCallback&&) noexcept = default;
  65. OnceCallback(RepeatingCallback<RunType> other)
  66. : internal::CallbackBase(std::move(other)) {}
  67. OnceCallback& operator=(RepeatingCallback<RunType> other) {
  68. static_cast<internal::CallbackBase&>(*this) = std::move(other);
  69. return *this;
  70. }
  71. R Run(Args... args) const & {
  72. static_assert(!sizeof(*this),
  73. "OnceCallback::Run() may only be invoked on a non-const "
  74. "rvalue, i.e. std::move(callback).Run().");
  75. NOTREACHED();
  76. }
  77. R Run(Args... args) && {
  78. // Move the callback instance into a local variable before the invocation,
  79. // that ensures the internal state is cleared after the invocation.
  80. // It's not safe to touch |this| after the invocation, since running the
  81. // bound function may destroy |this|.
  82. OnceCallback cb = std::move(*this);
  83. PolymorphicInvoke f =
  84. reinterpret_cast<PolymorphicInvoke>(cb.polymorphic_invoke());
  85. return f(cb.bind_state_.get(), std::forward<Args>(args)...);
  86. }
  87. };
  88. template <typename R, typename... Args>
  89. class RepeatingCallback<R(Args...)> : public internal::CallbackBaseCopyable {
  90. public:
  91. using RunType = R(Args...);
  92. using PolymorphicInvoke = R (*)(internal::BindStateBase*,
  93. internal::PassingType<Args>...);
  94. constexpr RepeatingCallback() = default;
  95. RepeatingCallback(std::nullptr_t) = delete;
  96. explicit RepeatingCallback(internal::BindStateBase* bind_state)
  97. : internal::CallbackBaseCopyable(bind_state) {}
  98. // Copyable and movable.
  99. RepeatingCallback(const RepeatingCallback&) = default;
  100. RepeatingCallback& operator=(const RepeatingCallback&) = default;
  101. RepeatingCallback(RepeatingCallback&&) noexcept = default;
  102. RepeatingCallback& operator=(RepeatingCallback&&) noexcept = default;
  103. bool operator==(const RepeatingCallback& other) const {
  104. return EqualsInternal(other);
  105. }
  106. bool operator!=(const RepeatingCallback& other) const {
  107. return !operator==(other);
  108. }
  109. R Run(Args... args) const & {
  110. PolymorphicInvoke f =
  111. reinterpret_cast<PolymorphicInvoke>(this->polymorphic_invoke());
  112. return f(this->bind_state_.get(), std::forward<Args>(args)...);
  113. }
  114. R Run(Args... args) && {
  115. // Move the callback instance into a local variable before the invocation,
  116. // that ensures the internal state is cleared after the invocation.
  117. // It's not safe to touch |this| after the invocation, since running the
  118. // bound function may destroy |this|.
  119. RepeatingCallback cb = std::move(*this);
  120. PolymorphicInvoke f =
  121. reinterpret_cast<PolymorphicInvoke>(cb.polymorphic_invoke());
  122. return f(std::move(cb).bind_state_.get(), std::forward<Args>(args)...);
  123. }
  124. };
  125. } // namespace base
  126. #endif // BASE_CALLBACK_H_