unique_function.h
1 // Copyright 2021 yuzu Emulator Project 2 // Licensed under GPLv2 or any later version 3 // Refer to the license.txt file included. 4 5 #pragma once 6 7 #include <memory> 8 #include <utility> 9 10 namespace Common { 11 12 /// General purpose function wrapper similar to std::function. 13 /// Unlike std::function, the captured values don't have to be copyable. 14 /// This class can be moved but not copied. 15 template <typename ResultType, typename... Args> 16 class UniqueFunction { 17 class CallableBase { 18 public: 19 virtual ~CallableBase() = default; 20 virtual ResultType operator()(Args&&...) = 0; 21 }; 22 23 template <typename Functor> 24 class Callable final : public CallableBase { 25 public: 26 Callable(Functor&& functor_) : functor{std::move(functor_)} {} 27 ~Callable() override = default; 28 29 ResultType operator()(Args&&... args) override { 30 return functor(std::forward<Args>(args)...); 31 } 32 33 private: 34 Functor functor; 35 }; 36 37 public: 38 UniqueFunction() = default; 39 40 template <typename Functor> 41 UniqueFunction(Functor&& functor) 42 : callable{std::make_unique<Callable<Functor>>(std::move(functor))} {} 43 44 UniqueFunction& operator=(UniqueFunction&& rhs) noexcept = default; 45 UniqueFunction(UniqueFunction&& rhs) noexcept = default; 46 47 UniqueFunction& operator=(const UniqueFunction&) = delete; 48 UniqueFunction(const UniqueFunction&) = delete; 49 50 ResultType operator()(Args&&... args) const { 51 return (*callable)(std::forward<Args>(args)...); 52 } 53 54 explicit operator bool() const noexcept { 55 return static_cast<bool>(callable); 56 } 57 58 private: 59 std::unique_ptr<CallableBase> callable; 60 }; 61 62 } // namespace Common