pineapple-src/src/common/unique_function.h

60 lines
1.5 KiB
C
Raw Normal View History

2021-07-05 17:19:14 -04:00
// Copyright 2021 yuzu emulator team
// Licensed under GPLv2 or any later version
// Refer to the license.txt file included.
#pragma once
#include <memory>
#include <utility>
namespace Common {
template <typename ResultType, typename... Args>
class UniqueFunction {
class CallableBase {
public:
virtual ~CallableBase() = default;
2021-07-07 16:12:25 -04:00
virtual ResultType operator()(Args&&...) = 0;
2021-07-05 17:19:14 -04:00
};
template <typename Functor>
class Callable final : public CallableBase {
public:
Callable(Functor&& functor_) : functor{std::move(functor_)} {}
~Callable() override = default;
2021-07-07 16:12:25 -04:00
ResultType operator()(Args&&... args) override {
2021-07-05 17:19:14 -04: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 16:12:25 -04:00
UniqueFunction& operator=(UniqueFunction&& rhs) noexcept = default;
UniqueFunction(UniqueFunction&& rhs) noexcept = default;
2021-07-05 17:19:14 -04:00
2021-07-07 16:12:25 -04:00
UniqueFunction& operator=(const UniqueFunction&) = delete;
UniqueFunction(const UniqueFunction&) = delete;
2021-07-05 17:19:14 -04:00
2021-07-07 16:12:25 -04:00
ResultType operator()(Args&&... args) const {
2021-07-05 17:19:14 -04:00
return (*callable)(std::forward<Args>(args)...);
}
explicit operator bool() const noexcept {
2021-07-07 16:12:25 -04:00
return static_cast<bool>(callable);
2021-07-05 17:19:14 -04:00
}
private:
std::unique_ptr<CallableBase> callable;
};
} // namespace Common