| OLD | NEW |
| (Empty) |
| 1 /* | |
| 2 * Copyright 2015 Google Inc. | |
| 3 * | |
| 4 * Use of this source code is governed by a BSD-style license that can be | |
| 5 * found in the LICENSE file. | |
| 6 */ | |
| 7 | |
| 8 #ifndef SkFunction_DEFINED | |
| 9 #define SkFunction_DEFINED | |
| 10 | |
| 11 // TODO: document, more pervasive move support in constructors, small-Fn optimiz
ation | |
| 12 | |
| 13 #include "SkUtility.h" | |
| 14 #include "SkUniquePtr.h" | |
| 15 #include "SkTypes.h" | |
| 16 | |
| 17 template <typename> class SkFunction; | |
| 18 | |
| 19 template <typename R, typename... Args> | |
| 20 class SkFunction<R(Args...)> { | |
| 21 public: | |
| 22 SkFunction() {} | |
| 23 | |
| 24 template <typename Fn> | |
| 25 SkFunction(const Fn& fn) | |
| 26 : fFunction(new LambdaImpl<Fn>(fn)) {} | |
| 27 | |
| 28 SkFunction(R (*fn)(Args...)) : fFunction(new FnPtrImpl(fn)) {} | |
| 29 | |
| 30 SkFunction(const SkFunction& other) { *this = other; } | |
| 31 SkFunction& operator=(const SkFunction& other) { | |
| 32 if (this != &other) { | |
| 33 fFunction.reset(other.fFunction.get() ? other.fFunction->clone() : n
ullptr); | |
| 34 } | |
| 35 return *this; | |
| 36 } | |
| 37 | |
| 38 R operator()(Args... args) const { | |
| 39 SkASSERT(fFunction.get()); | |
| 40 return fFunction->call(skstd::forward<Args>(args)...); | |
| 41 } | |
| 42 | |
| 43 private: | |
| 44 struct Interface { | |
| 45 virtual ~Interface() {} | |
| 46 virtual R call(Args...) const = 0; | |
| 47 virtual Interface* clone() const = 0; | |
| 48 }; | |
| 49 | |
| 50 template <typename Fn> | |
| 51 class LambdaImpl final : public Interface { | |
| 52 public: | |
| 53 LambdaImpl(const Fn& fn) : fFn(fn) {} | |
| 54 | |
| 55 R call(Args... args) const override { return fFn(skstd::forward<Args>(ar
gs)...); } | |
| 56 Interface* clone() const override { return new LambdaImpl<Fn>(fFn); } | |
| 57 | |
| 58 private: | |
| 59 Fn fFn; | |
| 60 }; | |
| 61 | |
| 62 class FnPtrImpl final : public Interface { | |
| 63 public: | |
| 64 FnPtrImpl(R (*fn)(Args...)) : fFn(fn) {} | |
| 65 | |
| 66 R call(Args... args) const override { return fFn(skstd::forward<Args>(ar
gs)...); } | |
| 67 Interface* clone() const override { return new FnPtrImpl(fFn); } | |
| 68 | |
| 69 private: | |
| 70 R (*fFn)(Args...); | |
| 71 }; | |
| 72 | |
| 73 skstd::unique_ptr<Interface> fFunction; | |
| 74 }; | |
| 75 | |
| 76 #endif//SkFunction_DEFINED | |
| OLD | NEW |