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 // This file contains utility functions and classes that help the
6 // implementation, and management of the Callback objects.
8 #ifndef BASE_CALLBACK_INTERNAL_H_
9 #define BASE_CALLBACK_INTERNAL_H_
13 #include "base/atomic_ref_count.h"
14 #include "base/base_export.h"
15 #include "base/macros.h"
16 #include "base/memory/ref_counted.h"
17 #include "base/memory/scoped_ptr.h"
18 #include "base/template_util.h"
27 // BindStateBase is used to provide an opaque handle that the Callback
28 // class can use to represent a function object with bound arguments. It
29 // behaves as an existential type that is used by a corresponding
30 // DoInvoke function to perform the function execution. This allows
31 // us to shield the Callback class from the types of the bound argument via
33 // At the base level, the only task is to add reference counting data. Don't use
34 // RefCountedThreadSafe since it requires the destructor to be a virtual method.
35 // Creating a vtable for every BindState template instantiation results in a lot
36 // of bloat. Its only task is to call the destructor which can be done with a
40 explicit BindStateBase(void (*destructor
)(BindStateBase
*))
41 : ref_count_(0), destructor_(destructor
) {}
42 ~BindStateBase() = default;
45 friend class scoped_refptr
<BindStateBase
>;
46 friend class CallbackBase
;
51 AtomicRefCount ref_count_
;
53 // Pointer to a function that will properly destroy |this|.
54 void (*destructor_
)(BindStateBase
*);
56 DISALLOW_COPY_AND_ASSIGN(BindStateBase
);
59 // Holds the Callback methods that don't require specialization to reduce
61 class BASE_EXPORT CallbackBase
{
63 CallbackBase(const CallbackBase
& c
);
64 CallbackBase
& operator=(const CallbackBase
& c
);
66 // Returns true if Callback is null (doesn't refer to anything).
67 bool is_null() const { return bind_state_
.get() == NULL
; }
69 // Returns the Callback into an uninitialized state.
73 // In C++, it is safe to cast function pointers to function pointers of
74 // another type. It is not okay to use void*. We create a InvokeFuncStorage
75 // that that can store our function pointer, and then cast it back to
76 // the original type on usage.
77 typedef void(*InvokeFuncStorage
)(void);
79 // Returns true if this callback equals |other|. |other| may be null.
80 bool Equals(const CallbackBase
& other
) const;
82 // Allow initializing of |bind_state_| via the constructor to avoid default
83 // initialization of the scoped_refptr. We do not also initialize
84 // |polymorphic_invoke_| here because doing a normal assignment in the
85 // derived Callback templates makes for much nicer compiler errors.
86 explicit CallbackBase(BindStateBase
* bind_state
);
88 // Force the destructor to be instantiated inside this translation unit so
89 // that our subclasses will not get inlined versions. Avoids more template
93 scoped_refptr
<BindStateBase
> bind_state_
;
94 InvokeFuncStorage polymorphic_invoke_
;
97 // A helper template to determine if given type is non-const move-only-type,
98 // i.e. if a value of the given type should be passed via .Pass() in a
100 template <typename T
> struct IsMoveOnlyType
{
101 template <typename U
>
102 static YesType
Test(const typename
U::MoveOnlyTypeForCPP03
*);
104 template <typename U
>
105 static NoType
Test(...);
107 static const bool value
= sizeof((Test
<T
>(0))) == sizeof(YesType
) &&
111 // Returns |Then| as SelectType::Type if |condition| is true. Otherwise returns
113 template <bool condition
, typename Then
, typename Else
>
118 template <typename Then
, typename Else
>
119 struct SelectType
<false, Then
, Else
> {
124 struct CallbackParamTraitsForMoveOnlyType
;
127 struct CallbackParamTraitsForNonMoveOnlyType
;
129 // TODO(tzik): Use a default parameter once MSVS supports variadic templates
130 // with default values.
131 // http://connect.microsoft.com/VisualStudio/feedbackdetail/view/957801/compilation-error-with-variadic-templates
133 // This is a typetraits object that's used to take an argument type, and
134 // extract a suitable type for storing and forwarding arguments.
136 // In particular, it strips off references, and converts arrays to
137 // pointers for storage; and it avoids accidentally trying to create a
138 // "reference of a reference" if the argument is a reference type.
140 // This array type becomes an issue for storage because we are passing bound
141 // parameters by const reference. In this case, we end up passing an actual
142 // array type in the initializer list which C++ does not allow. This will
143 // break passing of C-string literals.
144 template <typename T
>
145 struct CallbackParamTraits
146 : SelectType
<IsMoveOnlyType
<T
>::value
,
147 CallbackParamTraitsForMoveOnlyType
<T
>,
148 CallbackParamTraitsForNonMoveOnlyType
<T
> >::Type
{
151 template <typename T
>
152 struct CallbackParamTraitsForNonMoveOnlyType
{
153 typedef const T
& ForwardType
;
154 typedef T StorageType
;
157 // The Storage should almost be impossible to trigger unless someone manually
158 // specifies type of the bind parameters. However, in case they do,
159 // this will guard against us accidentally storing a reference parameter.
161 // The ForwardType should only be used for unbound arguments.
162 template <typename T
>
163 struct CallbackParamTraitsForNonMoveOnlyType
<T
&> {
164 typedef T
& ForwardType
;
165 typedef T StorageType
;
168 // Note that for array types, we implicitly add a const in the conversion. This
169 // means that it is not possible to bind array arguments to functions that take
170 // a non-const pointer. Trying to specialize the template based on a "const
171 // T[n]" does not seem to match correctly, so we are stuck with this
173 template <typename T
, size_t n
>
174 struct CallbackParamTraitsForNonMoveOnlyType
<T
[n
]> {
175 typedef const T
* ForwardType
;
176 typedef const T
* StorageType
;
179 // See comment for CallbackParamTraits<T[n]>.
180 template <typename T
>
181 struct CallbackParamTraitsForNonMoveOnlyType
<T
[]> {
182 typedef const T
* ForwardType
;
183 typedef const T
* StorageType
;
186 // Parameter traits for movable-but-not-copyable scopers.
188 // Callback<>/Bind() understands movable-but-not-copyable semantics where
189 // the type cannot be copied but can still have its state destructively
190 // transferred (aka. moved) to another instance of the same type by calling a
191 // helper function. When used with Bind(), this signifies transferal of the
192 // object's state to the target function.
194 // For these types, the ForwardType must not be a const reference, or a
195 // reference. A const reference is inappropriate, and would break const
196 // correctness, because we are implementing a destructive move. A non-const
197 // reference cannot be used with temporaries which means the result of a
198 // function or a cast would not be usable with Callback<> or Bind().
199 template <typename T
>
200 struct CallbackParamTraitsForMoveOnlyType
{
201 typedef T ForwardType
;
202 typedef T StorageType
;
205 // CallbackForward() is a very limited simulation of C++11's std::forward()
206 // used by the Callback/Bind system for a set of movable-but-not-copyable
207 // types. It is needed because forwarding a movable-but-not-copyable
208 // argument to another function requires us to invoke the proper move
209 // operator to create a rvalue version of the type. The supported types are
210 // whitelisted below as overloads of the CallbackForward() function. The
211 // default template compiles out to be a no-op.
213 // In C++11, std::forward would replace all uses of this function. However, it
214 // is impossible to implement a general std::forward with C++11 due to a lack
215 // of rvalue references.
217 // In addition to Callback/Bind, this is used by PostTaskAndReplyWithResult to
218 // simulate std::forward() and forward the result of one Callback as a
219 // parameter to another callback. This is to support Callbacks that return
220 // the movable-but-not-copyable types whitelisted above.
221 template <typename T
>
222 typename enable_if
<!IsMoveOnlyType
<T
>::value
, T
>::type
& CallbackForward(T
& t
) {
226 template <typename T
>
227 typename enable_if
<IsMoveOnlyType
<T
>::value
, T
>::type
CallbackForward(T
& t
) {
231 } // namespace internal
234 #endif // BASE_CALLBACK_INTERNAL_H_