forked from flutter/engine
-
Notifications
You must be signed in to change notification settings - Fork 0
/
make_copyable.h
63 lines (51 loc) · 1.77 KB
/
make_copyable.h
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef FLUTTER_FML_MAKE_COPYABLE_H_
#define FLUTTER_FML_MAKE_COPYABLE_H_
#include <utility>
#include "flutter/fml/memory/ref_counted.h"
#include "flutter/fml/memory/ref_ptr.h"
namespace fml {
namespace internal {
template <typename T>
class CopyableLambda {
public:
explicit CopyableLambda(T func)
: impl_(MakeRefCounted<Impl>(std::move(func))) {}
template <typename... ArgType>
auto operator()(ArgType&&... args) const {
return impl_->func_(std::forward<ArgType>(args)...);
}
private:
class Impl : public RefCountedThreadSafe<Impl> {
public:
explicit Impl(T func) : func_(std::move(func)) {}
T func_;
};
RefPtr<Impl> impl_;
};
} // namespace internal
// Provides a wrapper for a move-only lambda that is implictly convertable to an
// std::function.
//
// std::function is copyable, but if a lambda captures an argument with a
// move-only type, the lambda itself is not copyable. In order to use the lambda
// in places that accept std::functions, we provide a copyable object that wraps
// the lambda and is implicitly convertable to an std::function.
//
// EXAMPLE:
//
// std::unique_ptr<Foo> foo = ...
// std::function<int()> func =
// fml::MakeCopyable([bar = std::move(foo)]() { return bar->count(); });
//
// Notice that the return type of MakeCopyable is rarely used directly. Instead,
// callers typically erase the type by implicitly converting the return value
// to an std::function.
template <typename T>
internal::CopyableLambda<T> MakeCopyable(T lambda) {
return internal::CopyableLambda<T>(std::move(lambda));
}
} // namespace fml
#endif // FLUTTER_FML_MAKE_COPYABLE_H_