bind_helpers.h 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. // Copyright (c) 2011 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. #ifndef BASE_BIND_HELPERS_H_
  5. #define BASE_BIND_HELPERS_H_
  6. #include <stddef.h>
  7. #include <type_traits>
  8. #include <utility>
  9. #include "base/bind.h"
  10. #include "base/callback.h"
  11. #include "base/memory/weak_ptr.h"
  12. #include "build/build_config.h"
  13. // This defines a set of simple functions and utilities that people want when
  14. // using {Once,Repeating}Callback<> and Bind{Once,Repeating}().
  15. namespace base {
  16. // Creates a null callback.
  17. class BASE_EXPORT NullCallback {
  18. public:
  19. template <typename R, typename... Args>
  20. operator RepeatingCallback<R(Args...)>() const {
  21. return RepeatingCallback<R(Args...)>();
  22. }
  23. template <typename R, typename... Args>
  24. operator OnceCallback<R(Args...)>() const {
  25. return OnceCallback<R(Args...)>();
  26. }
  27. };
  28. // Creates a callback that does nothing when called.
  29. class BASE_EXPORT DoNothing {
  30. public:
  31. template <typename... Args>
  32. operator RepeatingCallback<void(Args...)>() const {
  33. return Repeatedly<Args...>();
  34. }
  35. template <typename... Args>
  36. operator OnceCallback<void(Args...)>() const {
  37. return Once<Args...>();
  38. }
  39. // Explicit way of specifying a specific callback type when the compiler can't
  40. // deduce it.
  41. template <typename... Args>
  42. static RepeatingCallback<void(Args...)> Repeatedly() {
  43. return BindRepeating([](Args... args) {});
  44. }
  45. template <typename... Args>
  46. static OnceCallback<void(Args...)> Once() {
  47. return BindOnce([](Args... args) {});
  48. }
  49. };
  50. // Useful for creating a Closure that will delete a pointer when invoked. Only
  51. // use this when necessary. In most cases MessageLoop::DeleteSoon() is a better
  52. // fit.
  53. template <typename T>
  54. void DeletePointer(T* obj) {
  55. delete obj;
  56. }
  57. } // namespace base
  58. #endif // BASE_BIND_HELPERS_H_