unique_function.h 1.7 KB

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