| 1 |
|
| 2 |
|
| 3 |
|
| 4 |
#pragma once |
| 5 |
|
| 6 |
#include <concepts> |
| 7 |
#include <functional> |
| 8 |
#include <memory> |
| 9 |
#include <type_traits> |
| 10 |
|
| 11 |
|
| 12 |
|
| 13 |
namespace Common |
| 14 |
{ |
| 15 |
|
| 16 |
template <typename T> |
| 17 |
class MoveOnlyFunction; |
| 18 |
|
| 19 |
template <typename R, typename... Args> |
| 20 |
class MoveOnlyFunction<R(Args...)> |
| 21 |
{ |
| 22 |
public: |
| 23 |
using result_type = R; |
| 24 |
|
| 25 |
MoveOnlyFunction() = default; |
| 26 |
|
| 27 |
template <std::invocable<Args...> F> |
| 28 |
requires(!std::same_as<std::decay_t<F>, MoveOnlyFunction>) |
| 29 |
MoveOnlyFunction(F&& f) : m_ptr{std::make_unique<Func<F>>(std::forward<F>(f))} |
| 30 |
{ |
| 31 |
} |
| 32 |
|
| 33 |
result_type operator()(Args... args) const { return m_ptr->Invoke(std::forward<Args>(args)...); } |
| 34 |
explicit operator bool() const { return m_ptr != nullptr; } |
| 35 |
void swap(MoveOnlyFunction& other) { m_ptr.swap(other.m_ptr); } |
| 36 |
|
| 37 |
private: |
| 38 |
struct FuncBase |
| 39 |
{ |
| 40 |
virtual ~FuncBase() = default; |
| 41 |
virtual result_type Invoke(Args...) = 0; |
| 42 |
}; |
| 43 |
|
| 44 |
template <typename F> |
| 45 |
struct Func : FuncBase |
| 46 |
{ |
| 47 |
explicit Func(F&& f) : func{std::forward<F>(f)} {} |
| 48 |
result_type Invoke(Args... args) override { return func(std::forward<Args>(args)...); } |
| 49 |
std::decay_t<F> func; |
| 50 |
}; |
| 51 |
|
| 52 |
std::unique_ptr<FuncBase> m_ptr; |
| 53 |
}; |
| 54 |
|
| 55 |
|
| 56 |
|
| 57 |
|
| 58 |
template <auto Invocable> |
| 59 |
struct InvokerOf |
| 60 |
{ |
| 61 |
template <typename... Args> |
| 62 |
constexpr auto operator()(Args... args) const |
| 63 |
{ |
| 64 |
return std::invoke(Invocable, std::forward<Args>(args)...); |
| 65 |
} |
| 66 |
}; |
| 67 |
|
| 68 |
} |