WPILibC++ 2024.3.2
function_ref.h
Go to the documentation of this file.
1// Copyright (c) FIRST and other WPILib contributors.
2// Open Source Software; you can modify and/or share it under the terms of
3// the WPILib BSD license file in the root directory of this project.
4
5//===- llvm/ADT/STLExtras.h - Useful STL related functions ------*- C++ -*-===//
6//
7// The LLVM Compiler Infrastructure
8//
9// This file is distributed under the University of Illinois Open Source
10// License. See LICENSE.TXT for details.
11//
12//===----------------------------------------------------------------------===//
13
14#ifndef WPIUTIL_WPI_FUNCTION_REF_H_
15#define WPIUTIL_WPI_FUNCTION_REF_H_
16
17#include <stdint.h>
18
19#include <type_traits>
20#include <utility>
21
22namespace wpi {
23
24/// An efficient, type-erasing, non-owning reference to a callable. This is
25/// intended for use as the type of a function parameter that is not used
26/// after the function in question returns.
27///
28/// This class does not own the callable, so it is not in general safe to store
29/// a function_ref.
30template <typename Fn>
32
33template <typename Ret, typename... Params>
34class function_ref<Ret(Params...)> {
35 Ret (*callback)(intptr_t callable, Params... params) = nullptr;
36 intptr_t callable;
37
38 template <typename Callable>
39 static Ret callback_fn(intptr_t callable, Params... params) {
40 return (*reinterpret_cast<Callable*>(callable))(std::forward<Params>(
41 params)...);
42 }
43
44 public:
45 function_ref() = default;
46 /*implicit*/ function_ref(std::nullptr_t) {} // NOLINT
47
48 template <typename Callable>
49 /*implicit*/ function_ref( // NOLINT
50 Callable&& callable,
51 typename std::enable_if<
52 !std::is_same<typename std::remove_reference<Callable>::type,
53 function_ref>::value>::type* = nullptr)
54 : callback(callback_fn<typename std::remove_reference<Callable>::type>),
55 callable(reinterpret_cast<intptr_t>(&callable)) {}
56
57 Ret operator()(Params... params) const {
58 return callback(callable, std::forward<Params>(params)...);
59 }
60
61 explicit operator bool() const { return callback; }
62};
63
64} // namespace wpi
65
66#endif // WPIUTIL_WPI_FUNCTION_REF_H_
Ret operator()(Params... params) const
Definition: function_ref.h:57
function_ref(std::nullptr_t)
Definition: function_ref.h:46
function_ref(Callable &&callable, typename std::enable_if< !std::is_same< typename std::remove_reference< Callable >::type, function_ref >::value >::type *=nullptr)
Definition: function_ref.h:49
An efficient, type-erasing, non-owning reference to a callable.
Definition: function_ref.h:31
type
Definition: core.h:556
Definition: array.h:89
Definition: ntcore_cpp.h:26