|
| 1 | +#ifndef MOVE_ONLY_FUNCTION_HPP |
| 2 | +#define MOVE_ONLY_FUNCTION_HPP |
| 3 | + |
| 4 | +#include <functional> |
| 5 | +#include <memory> |
| 6 | +#include <type_traits> |
| 7 | +#include <utility> |
| 8 | +#include <cstddef> |
| 9 | +#include "small_unique_ptr.hpp" |
| 10 | + |
| 11 | +template<typename...> |
| 12 | +class move_only_function; |
| 13 | + |
| 14 | +template<typename Ret, typename... Args> |
| 15 | +class move_only_function<Ret(Args...)> |
| 16 | +{ |
| 17 | +public: |
| 18 | + constexpr move_only_function() noexcept = default; |
| 19 | + constexpr move_only_function(std::nullptr_t) noexcept {} |
| 20 | + |
| 21 | + template<typename F> |
| 22 | + requires(!std::is_same_v<std::remove_reference_t<F>, move_only_function> && std::is_invocable_r_v<Ret, F&, Args...>) |
| 23 | + constexpr move_only_function(F&& f) : |
| 24 | + fptr_(smp::make_unique_small<Impl<std::decay_t<F>>>(std::forward<F>(f))) |
| 25 | + {} |
| 26 | + |
| 27 | + template<typename F> |
| 28 | + requires(!std::is_same_v<std::remove_reference_t<F>, move_only_function> && std::is_invocable_r_v<Ret, F&, Args...>) |
| 29 | + constexpr move_only_function& operator=(F&& f) |
| 30 | + { |
| 31 | + fptr_ = smp::make_unique_small<Impl<std::decay_t<F>>>(std::forward<F>(f)); |
| 32 | + return *this; |
| 33 | + } |
| 34 | + |
| 35 | + constexpr move_only_function(move_only_function&&) = default; |
| 36 | + constexpr move_only_function& operator=(move_only_function&&) = default; |
| 37 | + |
| 38 | + constexpr Ret operator()(Args... args) const |
| 39 | + { |
| 40 | + return fptr_->invoke(std::forward<Args>(args)...); |
| 41 | + } |
| 42 | + |
| 43 | + constexpr void swap(move_only_function& other) noexcept |
| 44 | + { |
| 45 | + fptr_.swap(other.fptr_); |
| 46 | + } |
| 47 | + |
| 48 | + constexpr explicit operator bool() const noexcept { return static_cast<bool>(fptr_); } |
| 49 | + |
| 50 | +private: |
| 51 | + struct ImplBase |
| 52 | + { |
| 53 | + constexpr virtual Ret invoke(Args...) = 0; |
| 54 | + constexpr virtual void small_unique_ptr_move(void* dst) noexcept = 0; |
| 55 | + constexpr virtual ~ImplBase() = default; |
| 56 | + }; |
| 57 | + |
| 58 | + template<typename Callable> |
| 59 | + struct Impl : public ImplBase |
| 60 | + { |
| 61 | + constexpr Impl(Callable func) noexcept(std::is_nothrow_move_constructible_v<Callable>) : |
| 62 | + func_(std::move(func)) |
| 63 | + {} |
| 64 | + |
| 65 | + constexpr void small_unique_ptr_move(void* dst) noexcept override |
| 66 | + { |
| 67 | + std::construct_at(static_cast<Impl*>(dst), std::move(*this)); |
| 68 | + } |
| 69 | + |
| 70 | + constexpr Ret invoke(Args... args) override |
| 71 | + { |
| 72 | + return std::invoke(func_, std::forward<Args>(args)...); |
| 73 | + } |
| 74 | + |
| 75 | + Callable func_; |
| 76 | + }; |
| 77 | + |
| 78 | + smp::small_unique_ptr<ImplBase> fptr_ = nullptr; |
| 79 | +}; |
| 80 | + |
| 81 | +#endif // !MOVE_ONLY_FUNCTION_HPP |
0 commit comments