unique_function.h 1.6 KB

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