Blink roll 25b6bd3a7a131ffe68d809546ad1a20707915cdc:3a503f41ae42e5b79cfcd2ff10e65afde...
[chromium-blink-merge.git] / base / mac / bind_objc_block.h
blobc31f26e5a31f6347fc2459848f0d261a8e4c4bf4
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 #ifndef BASE_MAC_BIND_OBJC_BLOCK_H_
6 #define BASE_MAC_BIND_OBJC_BLOCK_H_
8 #include <Block.h>
10 #include "base/bind.h"
11 #include "base/callback_forward.h"
12 #include "base/mac/scoped_block.h"
14 // BindBlock builds a callback from an Objective-C block. Example usages:
16 // Closure closure = BindBlock(^{DoSomething();});
18 // Callback<int(void)> callback = BindBlock(^{return 42;});
20 // Callback<void(const std::string&, const std::string&)> callback =
21 // BindBlock(^(const std::string& arg0, const std::string& arg1) {
22 // ...
23 // });
25 // These variadic templates will accommodate any number of arguments, however
26 // the underlying templates in bind_internal.h and callback.h are limited to
27 // seven total arguments, and the bound block itself is used as one of these
28 // arguments, so functionally the templates are limited to binding blocks with
29 // zero through six arguments.
31 namespace base {
33 namespace internal {
35 // Helper function to run the block contained in the parameter.
36 template<typename R, typename... Args>
37 R RunBlock(base::mac::ScopedBlock<R(^)(Args...)> block, Args... args) {
38 R(^extracted_block)(Args...) = block.get();
39 return extracted_block(args...);
42 } // namespace internal
44 // Construct a callback from an objective-C block with up to six arguments (see
45 // note above).
46 template<typename R, typename... Args>
47 base::Callback<R(Args...)> BindBlock(R(^block)(Args...)) {
48 return base::Bind(&base::internal::RunBlock<R, Args...>,
49 base::mac::ScopedBlock<R(^)(Args...)>(Block_copy(block)));
52 } // namespace base
54 #endif // BASE_MAC_BIND_OBJC_BLOCK_H_