michael@0: // Copyright (c) 2011 The Chromium Authors. All rights reserved. michael@0: // Use of this source code is governed by a BSD-style license that can be michael@0: // found in the LICENSE file. michael@0: michael@0: // This defines a set of argument wrappers and related factory methods that michael@0: // can be used specify the refcounting and reference semantics of arguments michael@0: // that are bound by the Bind() function in base/bind.h. michael@0: // michael@0: // It also defines a set of simple functions and utilities that people want michael@0: // when using Callback<> and Bind(). michael@0: // michael@0: // michael@0: // ARGUMENT BINDING WRAPPERS michael@0: // michael@0: // The wrapper functions are base::Unretained(), base::Owned(), bass::Passed(), michael@0: // base::ConstRef(), and base::IgnoreResult(). michael@0: // michael@0: // Unretained() allows Bind() to bind a non-refcounted class, and to disable michael@0: // refcounting on arguments that are refcounted objects. michael@0: // michael@0: // Owned() transfers ownership of an object to the Callback resulting from michael@0: // bind; the object will be deleted when the Callback is deleted. michael@0: // michael@0: // Passed() is for transferring movable-but-not-copyable types (eg. scoped_ptr) michael@0: // through a Callback. Logically, this signifies a destructive transfer of michael@0: // the state of the argument into the target function. Invoking michael@0: // Callback::Run() twice on a Callback that was created with a Passed() michael@0: // argument will CHECK() because the first invocation would have already michael@0: // transferred ownership to the target function. michael@0: // michael@0: // ConstRef() allows binding a constant reference to an argument rather michael@0: // than a copy. michael@0: // michael@0: // IgnoreResult() is used to adapt a function or Callback with a return type to michael@0: // one with a void return. This is most useful if you have a function with, michael@0: // say, a pesky ignorable bool return that you want to use with PostTask or michael@0: // something else that expect a Callback with a void return. michael@0: // michael@0: // EXAMPLE OF Unretained(): michael@0: // michael@0: // class Foo { michael@0: // public: michael@0: // void func() { cout << "Foo:f" << endl; } michael@0: // }; michael@0: // michael@0: // // In some function somewhere. michael@0: // Foo foo; michael@0: // Closure foo_callback = michael@0: // Bind(&Foo::func, Unretained(&foo)); michael@0: // foo_callback.Run(); // Prints "Foo:f". michael@0: // michael@0: // Without the Unretained() wrapper on |&foo|, the above call would fail michael@0: // to compile because Foo does not support the AddRef() and Release() methods. michael@0: // michael@0: // michael@0: // EXAMPLE OF Owned(): michael@0: // michael@0: // void foo(int* arg) { cout << *arg << endl } michael@0: // michael@0: // int* pn = new int(1); michael@0: // Closure foo_callback = Bind(&foo, Owned(pn)); michael@0: // michael@0: // foo_callback.Run(); // Prints "1" michael@0: // foo_callback.Run(); // Prints "1" michael@0: // *n = 2; michael@0: // foo_callback.Run(); // Prints "2" michael@0: // michael@0: // foo_callback.Reset(); // |pn| is deleted. Also will happen when michael@0: // // |foo_callback| goes out of scope. michael@0: // michael@0: // Without Owned(), someone would have to know to delete |pn| when the last michael@0: // reference to the Callback is deleted. michael@0: // michael@0: // michael@0: // EXAMPLE OF ConstRef(): michael@0: // michael@0: // void foo(int arg) { cout << arg << endl } michael@0: // michael@0: // int n = 1; michael@0: // Closure no_ref = Bind(&foo, n); michael@0: // Closure has_ref = Bind(&foo, ConstRef(n)); michael@0: // michael@0: // no_ref.Run(); // Prints "1" michael@0: // has_ref.Run(); // Prints "1" michael@0: // michael@0: // n = 2; michael@0: // no_ref.Run(); // Prints "1" michael@0: // has_ref.Run(); // Prints "2" michael@0: // michael@0: // Note that because ConstRef() takes a reference on |n|, |n| must outlive all michael@0: // its bound callbacks. michael@0: // michael@0: // michael@0: // EXAMPLE OF IgnoreResult(): michael@0: // michael@0: // int DoSomething(int arg) { cout << arg << endl; } michael@0: // michael@0: // // Assign to a Callback with a void return type. michael@0: // Callback cb = Bind(IgnoreResult(&DoSomething)); michael@0: // cb->Run(1); // Prints "1". michael@0: // michael@0: // // Prints "1" on |ml|. michael@0: // ml->PostTask(FROM_HERE, Bind(IgnoreResult(&DoSomething), 1); michael@0: // michael@0: // michael@0: // EXAMPLE OF Passed(): michael@0: // michael@0: // void TakesOwnership(scoped_ptr arg) { } michael@0: // scoped_ptr CreateFoo() { return scoped_ptr(new Foo()); } michael@0: // michael@0: // scoped_ptr f(new Foo()); michael@0: // michael@0: // // |cb| is given ownership of Foo(). |f| is now NULL. michael@0: // // You can use f.Pass() in place of &f, but it's more verbose. michael@0: // Closure cb = Bind(&TakesOwnership, Passed(&f)); michael@0: // michael@0: // // Run was never called so |cb| still owns Foo() and deletes michael@0: // // it on Reset(). michael@0: // cb.Reset(); michael@0: // michael@0: // // |cb| is given a new Foo created by CreateFoo(). michael@0: // cb = Bind(&TakesOwnership, Passed(CreateFoo())); michael@0: // michael@0: // // |arg| in TakesOwnership() is given ownership of Foo(). |cb| michael@0: // // no longer owns Foo() and, if reset, would not delete Foo(). michael@0: // cb.Run(); // Foo() is now transferred to |arg| and deleted. michael@0: // cb.Run(); // This CHECK()s since Foo() already been used once. michael@0: // michael@0: // Passed() is particularly useful with PostTask() when you are transferring michael@0: // ownership of an argument into a task, but don't necessarily know if the michael@0: // task will always be executed. This can happen if the task is cancellable michael@0: // or if it is posted to a MessageLoopProxy. michael@0: // michael@0: // michael@0: // SIMPLE FUNCTIONS AND UTILITIES. michael@0: // michael@0: // DoNothing() - Useful for creating a Closure that does nothing when called. michael@0: // DeletePointer() - Useful for creating a Closure that will delete a michael@0: // pointer when invoked. Only use this when necessary. michael@0: // In most cases MessageLoop::DeleteSoon() is a better michael@0: // fit. michael@0: michael@0: #ifndef BASE_BIND_HELPERS_H_ michael@0: #define BASE_BIND_HELPERS_H_ michael@0: michael@0: #include "base/basictypes.h" michael@0: #include "base/callback.h" michael@0: #include "base/memory/weak_ptr.h" michael@0: #include "base/template_util.h" michael@0: michael@0: namespace base { michael@0: namespace internal { michael@0: michael@0: // Use the Substitution Failure Is Not An Error (SFINAE) trick to inspect T michael@0: // for the existence of AddRef() and Release() functions of the correct michael@0: // signature. michael@0: // michael@0: // http://en.wikipedia.org/wiki/Substitution_failure_is_not_an_error michael@0: // http://stackoverflow.com/questions/257288/is-it-possible-to-write-a-c-template-to-check-for-a-functions-existence michael@0: // http://stackoverflow.com/questions/4358584/sfinae-approach-comparison michael@0: // http://stackoverflow.com/questions/1966362/sfinae-to-check-for-inherited-member-functions michael@0: // michael@0: // The last link in particular show the method used below. michael@0: // michael@0: // For SFINAE to work with inherited methods, we need to pull some extra tricks michael@0: // with multiple inheritance. In the more standard formulation, the overloads michael@0: // of Check would be: michael@0: // michael@0: // template michael@0: // Yes NotTheCheckWeWant(Helper<&C::TargetFunc>*); michael@0: // michael@0: // template michael@0: // No NotTheCheckWeWant(...); michael@0: // michael@0: // static const bool value = sizeof(NotTheCheckWeWant(0)) == sizeof(Yes); michael@0: // michael@0: // The problem here is that template resolution will not match michael@0: // C::TargetFunc if TargetFunc does not exist directly in C. That is, if michael@0: // TargetFunc in inherited from an ancestor, &C::TargetFunc will not match, michael@0: // |value| will be false. This formulation only checks for whether or michael@0: // not TargetFunc exist directly in the class being introspected. michael@0: // michael@0: // To get around this, we play a dirty trick with multiple inheritance. michael@0: // First, We create a class BaseMixin that declares each function that we michael@0: // want to probe for. Then we create a class Base that inherits from both T michael@0: // (the class we wish to probe) and BaseMixin. Note that the function michael@0: // signature in BaseMixin does not need to match the signature of the function michael@0: // we are probing for; thus it's easiest to just use void(void). michael@0: // michael@0: // Now, if TargetFunc exists somewhere in T, then &Base::TargetFunc has an michael@0: // ambiguous resolution between BaseMixin and T. This lets us write the michael@0: // following: michael@0: // michael@0: // template michael@0: // No GoodCheck(Helper<&C::TargetFunc>*); michael@0: // michael@0: // template michael@0: // Yes GoodCheck(...); michael@0: // michael@0: // static const bool value = sizeof(GoodCheck(0)) == sizeof(Yes); michael@0: // michael@0: // Notice here that the variadic version of GoodCheck() returns Yes here michael@0: // instead of No like the previous one. Also notice that we calculate |value| michael@0: // by specializing GoodCheck() on Base instead of T. michael@0: // michael@0: // We've reversed the roles of the variadic, and Helper overloads. michael@0: // GoodCheck(Helper<&C::TargetFunc>*), when C = Base, fails to be a valid michael@0: // substitution if T::TargetFunc exists. Thus GoodCheck(0) will resolve michael@0: // to the variadic version if T has TargetFunc. If T::TargetFunc does not michael@0: // exist, then &C::TargetFunc is not ambiguous, and the overload resolution michael@0: // will prefer GoodCheck(Helper<&C::TargetFunc>*). michael@0: // michael@0: // This method of SFINAE will correctly probe for inherited names, but it cannot michael@0: // typecheck those names. It's still a good enough sanity check though. michael@0: // michael@0: // Works on gcc-4.2, gcc-4.4, and Visual Studio 2008. michael@0: // michael@0: // TODO(ajwong): Move to ref_counted.h or template_util.h when we've vetted michael@0: // this works well. michael@0: // michael@0: // TODO(ajwong): Make this check for Release() as well. michael@0: // See http://crbug.com/82038. michael@0: template michael@0: class SupportsAddRefAndRelease { michael@0: typedef char Yes[1]; michael@0: typedef char No[2]; michael@0: michael@0: struct BaseMixin { michael@0: void AddRef(); michael@0: }; michael@0: michael@0: // MSVC warns when you try to use Base if T has a private destructor, the michael@0: // common pattern for refcounted types. It does this even though no attempt to michael@0: // instantiate Base is made. We disable the warning for this definition. michael@0: #if defined(OS_WIN) michael@0: #pragma warning(push) michael@0: #pragma warning(disable:4624) michael@0: #endif michael@0: struct Base : public T, public BaseMixin { michael@0: }; michael@0: #if defined(OS_WIN) michael@0: #pragma warning(pop) michael@0: #endif michael@0: michael@0: template struct Helper {}; michael@0: michael@0: template michael@0: static No& Check(Helper<&C::AddRef>*); michael@0: michael@0: template michael@0: static Yes& Check(...); michael@0: michael@0: public: michael@0: static const bool value = sizeof(Check(0)) == sizeof(Yes); michael@0: }; michael@0: michael@0: // Helpers to assert that arguments of a recounted type are bound with a michael@0: // scoped_refptr. michael@0: template michael@0: struct UnsafeBindtoRefCountedArgHelper : false_type { michael@0: }; michael@0: michael@0: template michael@0: struct UnsafeBindtoRefCountedArgHelper michael@0: : integral_constant::value> { michael@0: }; michael@0: michael@0: template michael@0: struct UnsafeBindtoRefCountedArg : false_type { michael@0: }; michael@0: michael@0: template michael@0: struct UnsafeBindtoRefCountedArg michael@0: : UnsafeBindtoRefCountedArgHelper::value, T> { michael@0: }; michael@0: michael@0: template michael@0: class HasIsMethodTag { michael@0: typedef char Yes[1]; michael@0: typedef char No[2]; michael@0: michael@0: template michael@0: static Yes& Check(typename U::IsMethod*); michael@0: michael@0: template michael@0: static No& Check(...); michael@0: michael@0: public: michael@0: static const bool value = sizeof(Check(0)) == sizeof(Yes); michael@0: }; michael@0: michael@0: template michael@0: class UnretainedWrapper { michael@0: public: michael@0: explicit UnretainedWrapper(T* o) : ptr_(o) {} michael@0: T* get() const { return ptr_; } michael@0: private: michael@0: T* ptr_; michael@0: }; michael@0: michael@0: template michael@0: class ConstRefWrapper { michael@0: public: michael@0: explicit ConstRefWrapper(const T& o) : ptr_(&o) {} michael@0: const T& get() const { return *ptr_; } michael@0: private: michael@0: const T* ptr_; michael@0: }; michael@0: michael@0: template michael@0: struct IgnoreResultHelper { michael@0: explicit IgnoreResultHelper(T functor) : functor_(functor) {} michael@0: michael@0: T functor_; michael@0: }; michael@0: michael@0: template michael@0: struct IgnoreResultHelper > { michael@0: explicit IgnoreResultHelper(const Callback& functor) : functor_(functor) {} michael@0: michael@0: const Callback& functor_; michael@0: }; michael@0: michael@0: // An alternate implementation is to avoid the destructive copy, and instead michael@0: // specialize ParamTraits<> for OwnedWrapper<> to change the StorageType to michael@0: // a class that is essentially a scoped_ptr<>. michael@0: // michael@0: // The current implementation has the benefit though of leaving ParamTraits<> michael@0: // fully in callback_internal.h as well as avoiding type conversions during michael@0: // storage. michael@0: template michael@0: class OwnedWrapper { michael@0: public: michael@0: explicit OwnedWrapper(T* o) : ptr_(o) {} michael@0: ~OwnedWrapper() { delete ptr_; } michael@0: T* get() const { return ptr_; } michael@0: OwnedWrapper(const OwnedWrapper& other) { michael@0: ptr_ = other.ptr_; michael@0: other.ptr_ = NULL; michael@0: } michael@0: michael@0: private: michael@0: mutable T* ptr_; michael@0: }; michael@0: michael@0: // PassedWrapper is a copyable adapter for a scoper that ignores const. michael@0: // michael@0: // It is needed to get around the fact that Bind() takes a const reference to michael@0: // all its arguments. Because Bind() takes a const reference to avoid michael@0: // unnecessary copies, it is incompatible with movable-but-not-copyable michael@0: // types; doing a destructive "move" of the type into Bind() would violate michael@0: // the const correctness. michael@0: // michael@0: // This conundrum cannot be solved without either C++11 rvalue references or michael@0: // a O(2^n) blowup of Bind() templates to handle each combination of regular michael@0: // types and movable-but-not-copyable types. Thus we introduce a wrapper type michael@0: // that is copyable to transmit the correct type information down into michael@0: // BindState<>. Ignoring const in this type makes sense because it is only michael@0: // created when we are explicitly trying to do a destructive move. michael@0: // michael@0: // Two notes: michael@0: // 1) PassedWrapper supports any type that has a "Pass()" function. michael@0: // This is intentional. The whitelisting of which specific types we michael@0: // support is maintained by CallbackParamTraits<>. michael@0: // 2) is_valid_ is distinct from NULL because it is valid to bind a "NULL" michael@0: // scoper to a Callback and allow the Callback to execute once. michael@0: template michael@0: class PassedWrapper { michael@0: public: michael@0: explicit PassedWrapper(T scoper) : is_valid_(true), scoper_(scoper.Pass()) {} michael@0: PassedWrapper(const PassedWrapper& other) michael@0: : is_valid_(other.is_valid_), scoper_(other.scoper_.Pass()) { michael@0: } michael@0: T Pass() const { michael@0: CHECK(is_valid_); michael@0: is_valid_ = false; michael@0: return scoper_.Pass(); michael@0: } michael@0: michael@0: private: michael@0: mutable bool is_valid_; michael@0: mutable T scoper_; michael@0: }; michael@0: michael@0: // Unwrap the stored parameters for the wrappers above. michael@0: template michael@0: struct UnwrapTraits { michael@0: typedef const T& ForwardType; michael@0: static ForwardType Unwrap(const T& o) { return o; } michael@0: }; michael@0: michael@0: template michael@0: struct UnwrapTraits > { michael@0: typedef T* ForwardType; michael@0: static ForwardType Unwrap(UnretainedWrapper unretained) { michael@0: return unretained.get(); michael@0: } michael@0: }; michael@0: michael@0: template michael@0: struct UnwrapTraits > { michael@0: typedef const T& ForwardType; michael@0: static ForwardType Unwrap(ConstRefWrapper const_ref) { michael@0: return const_ref.get(); michael@0: } michael@0: }; michael@0: michael@0: template michael@0: struct UnwrapTraits > { michael@0: typedef T* ForwardType; michael@0: static ForwardType Unwrap(const scoped_refptr& o) { return o.get(); } michael@0: }; michael@0: michael@0: template michael@0: struct UnwrapTraits > { michael@0: typedef const WeakPtr& ForwardType; michael@0: static ForwardType Unwrap(const WeakPtr& o) { return o; } michael@0: }; michael@0: michael@0: template michael@0: struct UnwrapTraits > { michael@0: typedef T* ForwardType; michael@0: static ForwardType Unwrap(const OwnedWrapper& o) { michael@0: return o.get(); michael@0: } michael@0: }; michael@0: michael@0: template michael@0: struct UnwrapTraits > { michael@0: typedef T ForwardType; michael@0: static T Unwrap(PassedWrapper& o) { michael@0: return o.Pass(); michael@0: } michael@0: }; michael@0: michael@0: // Utility for handling different refcounting semantics in the Bind() michael@0: // function. michael@0: template michael@0: struct MaybeRefcount; michael@0: michael@0: template michael@0: struct MaybeRefcount { michael@0: static void AddRef(const T&) {} michael@0: static void Release(const T&) {} michael@0: }; michael@0: michael@0: template michael@0: struct MaybeRefcount { michael@0: static void AddRef(const T*) {} michael@0: static void Release(const T*) {} michael@0: }; michael@0: michael@0: template michael@0: struct MaybeRefcount { michael@0: static void AddRef(const T&) {} michael@0: static void Release(const T&) {} michael@0: }; michael@0: michael@0: template michael@0: struct MaybeRefcount { michael@0: static void AddRef(T* o) { o->AddRef(); } michael@0: static void Release(T* o) { o->Release(); } michael@0: }; michael@0: michael@0: // No need to additionally AddRef() and Release() since we are storing a michael@0: // scoped_refptr<> inside the storage object already. michael@0: template michael@0: struct MaybeRefcount > { michael@0: static void AddRef(const scoped_refptr& o) {} michael@0: static void Release(const scoped_refptr& o) {} michael@0: }; michael@0: michael@0: template michael@0: struct MaybeRefcount { michael@0: static void AddRef(const T* o) { o->AddRef(); } michael@0: static void Release(const T* o) { o->Release(); } michael@0: }; michael@0: michael@0: // IsWeakMethod is a helper that determine if we are binding a WeakPtr<> to a michael@0: // method. It is used internally by Bind() to select the correct michael@0: // InvokeHelper that will no-op itself in the event the WeakPtr<> for michael@0: // the target object is invalidated. michael@0: // michael@0: // P1 should be the type of the object that will be received of the method. michael@0: template michael@0: struct IsWeakMethod : public false_type {}; michael@0: michael@0: template michael@0: struct IsWeakMethod > : public true_type {}; michael@0: michael@0: template michael@0: struct IsWeakMethod > > : public true_type {}; michael@0: michael@0: } // namespace internal michael@0: michael@0: template michael@0: static inline internal::UnretainedWrapper Unretained(T* o) { michael@0: return internal::UnretainedWrapper(o); michael@0: } michael@0: michael@0: template michael@0: static inline internal::ConstRefWrapper ConstRef(const T& o) { michael@0: return internal::ConstRefWrapper(o); michael@0: } michael@0: michael@0: template michael@0: static inline internal::OwnedWrapper Owned(T* o) { michael@0: return internal::OwnedWrapper(o); michael@0: } michael@0: michael@0: // We offer 2 syntaxes for calling Passed(). The first takes a temporary and michael@0: // is best suited for use with the return value of a function. The second michael@0: // takes a pointer to the scoper and is just syntactic sugar to avoid having michael@0: // to write Passed(scoper.Pass()). michael@0: template michael@0: static inline internal::PassedWrapper Passed(T scoper) { michael@0: return internal::PassedWrapper(scoper.Pass()); michael@0: } michael@0: template michael@0: static inline internal::PassedWrapper Passed(T* scoper) { michael@0: return internal::PassedWrapper(scoper->Pass()); michael@0: } michael@0: michael@0: template michael@0: static inline internal::IgnoreResultHelper IgnoreResult(T data) { michael@0: return internal::IgnoreResultHelper(data); michael@0: } michael@0: michael@0: template michael@0: static inline internal::IgnoreResultHelper > michael@0: IgnoreResult(const Callback& data) { michael@0: return internal::IgnoreResultHelper >(data); michael@0: } michael@0: michael@0: BASE_EXPORT void DoNothing(); michael@0: michael@0: template michael@0: void DeletePointer(T* obj) { michael@0: delete obj; michael@0: } michael@0: michael@0: } // namespace base michael@0: michael@0: #endif // BASE_BIND_HELPERS_H_