Merge pull request #14026 from jordan-woyak/move-only-function-fix

Common/Functional: Fix MoveOnlyFunction from inadvertently creating references from lvalues.
This commit is contained in:
Admiral H. Curtiss 2025-11-09 14:49:20 +01:00 committed by GitHub
commit 6435ee1d20
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194

View File

@ -3,7 +3,9 @@
#pragma once
#include <concepts>
#include <memory>
#include <type_traits>
// TODO C++23: Replace with std::move_only_function.
@ -21,13 +23,14 @@ public:
MoveOnlyFunction() = default;
template <typename F>
template <std::invocable<Args...> F>
requires(!std::same_as<std::decay_t<F>, MoveOnlyFunction>)
MoveOnlyFunction(F&& f) : m_ptr{std::make_unique<Func<F>>(std::forward<F>(f))}
{
}
result_type operator()(Args... args) const { return m_ptr->Invoke(std::forward<Args>(args)...); }
explicit operator bool() const { return m_ptr != nullptr; };
explicit operator bool() const { return m_ptr != nullptr; }
void swap(MoveOnlyFunction& other) { m_ptr.swap(other.m_ptr); }
private:
@ -40,9 +43,9 @@ private:
template <typename F>
struct Func : FuncBase
{
Func(F&& f) : func{std::forward<F>(f)} {}
explicit Func(F&& f) : func{std::forward<F>(f)} {}
result_type Invoke(Args... args) override { return func(std::forward<Args>(args)...); }
F func;
std::decay_t<F> func;
};
std::unique_ptr<FuncBase> m_ptr;