TPDE
Loading...
Searching...
No Matches
function_ref.hpp
1// SPDX-FileCopyrightText: 2025 Contributors to TPDE <https://tpde.org>
2// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
3#pragma once
4
5#include <type_traits>
6#include <utility>
7
8namespace tpde::util {
9
10template <typename F>
11class function_ref;
12
13template <typename R, typename... Args>
14class function_ref<R(Args...)> {
15 R (*call)(void *fn, Args... args) = nullptr;
16 void *fn;
17
18public:
19 function_ref(const function_ref &) = default;
20
21 template <typename F>
22 function_ref(F &&fn)
23 requires std::is_invocable_r_v<R, F, Args...>
24 : fn(const_cast<void *>(static_cast<const void *>(&fn))) {
25 call = [](void *fn, Args... args) -> R {
26 return (*static_cast<std::remove_reference_t<F> *>(fn))(
27 std::forward<Args>(args)...);
28 };
29 }
30
31 R operator()(Args... args) const {
32 return call(fn, std::forward<Args>(args)...);
33 }
34};
35
36} // namespace tpde::util