2022-04-23 20:49:07 +02:00
|
|
|
// SPDX-FileCopyrightText: Copyright 2021 yuzu Emulator Project
|
|
|
|
// SPDX-License-Identifier: GPL-2.0-or-later
|
2021-07-05 23:19:14 +02:00
|
|
|
|
|
|
|
#pragma once
|
|
|
|
|
|
|
|
#include <memory>
|
|
|
|
#include <utility>
|
|
|
|
|
|
|
|
namespace Common {
|
|
|
|
|
2021-07-09 02:33:25 +02:00
|
|
|
/// General purpose function wrapper similar to std::function.
|
|
|
|
/// Unlike std::function, the captured values don't have to be copyable.
|
|
|
|
/// This class can be moved but not copied.
|
2021-07-05 23:19:14 +02:00
|
|
|
template <typename ResultType, typename... Args>
|
|
|
|
class UniqueFunction {
|
|
|
|
class CallableBase {
|
|
|
|
public:
|
|
|
|
virtual ~CallableBase() = default;
|
2021-07-07 22:12:25 +02:00
|
|
|
virtual ResultType operator()(Args&&...) = 0;
|
2021-07-05 23:19:14 +02:00
|
|
|
};
|
|
|
|
|
|
|
|
template <typename Functor>
|
|
|
|
class Callable final : public CallableBase {
|
|
|
|
public:
|
|
|
|
Callable(Functor&& functor_) : functor{std::move(functor_)} {}
|
|
|
|
~Callable() override = default;
|
|
|
|
|
2021-07-07 22:12:25 +02:00
|
|
|
ResultType operator()(Args&&... args) override {
|
2021-07-05 23:19:14 +02:00
|
|
|
return functor(std::forward<Args>(args)...);
|
|
|
|
}
|
|
|
|
|
|
|
|
private:
|
|
|
|
Functor functor;
|
|
|
|
};
|
|
|
|
|
|
|
|
public:
|
|
|
|
UniqueFunction() = default;
|
|
|
|
|
|
|
|
template <typename Functor>
|
|
|
|
UniqueFunction(Functor&& functor)
|
|
|
|
: callable{std::make_unique<Callable<Functor>>(std::move(functor))} {}
|
|
|
|
|
2021-07-07 22:12:25 +02:00
|
|
|
UniqueFunction& operator=(UniqueFunction&& rhs) noexcept = default;
|
|
|
|
UniqueFunction(UniqueFunction&& rhs) noexcept = default;
|
2021-07-05 23:19:14 +02:00
|
|
|
|
2021-07-07 22:12:25 +02:00
|
|
|
UniqueFunction& operator=(const UniqueFunction&) = delete;
|
|
|
|
UniqueFunction(const UniqueFunction&) = delete;
|
2021-07-05 23:19:14 +02:00
|
|
|
|
2021-07-07 22:12:25 +02:00
|
|
|
ResultType operator()(Args&&... args) const {
|
2021-07-05 23:19:14 +02:00
|
|
|
return (*callable)(std::forward<Args>(args)...);
|
|
|
|
}
|
|
|
|
|
|
|
|
explicit operator bool() const noexcept {
|
2021-07-07 22:12:25 +02:00
|
|
|
return static_cast<bool>(callable);
|
2021-07-05 23:19:14 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
private:
|
|
|
|
std::unique_ptr<CallableBase> callable;
|
|
|
|
};
|
|
|
|
|
|
|
|
} // namespace Common
|