[libc-commits] [libc] [llvm] [libc] Rename cpp::function to cpp::function_ref (PR #236108)
Jeff Bailey via libc-commits
libc-commits at lists.llvm.org
Wed Oct 28 05:00:52 PDT 2026
================
@@ -1,53 +1,64 @@
-//===-- Self contained functional header ------------------------*- C++ -*-===//
+//===----------------------------------------------------------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
+///
+/// \file
+/// Implementation of cpp::function_ref.
+///
+//===----------------------------------------------------------------------===//
#ifndef LLVM_LIBC_SRC___SUPPORT_CPP_FUNCTIONAL_H
#define LLVM_LIBC_SRC___SUPPORT_CPP_FUNCTIONAL_H
#include "hdr/stdint_proxy.h"
#include "src/__support/CPP/type_traits/enable_if.h"
#include "src/__support/CPP/type_traits/is_convertible.h"
+#include "src/__support/CPP/type_traits/is_function.h"
+#include "src/__support/CPP/type_traits/is_pointer.h"
#include "src/__support/CPP/type_traits/is_same.h"
#include "src/__support/CPP/type_traits/is_void.h"
#include "src/__support/CPP/type_traits/remove_cvref.h"
#include "src/__support/CPP/type_traits/remove_reference.h"
+#include "src/__support/CPP/utility/declval.h"
#include "src/__support/CPP/utility/forward.h"
#include "src/__support/macros/attributes.h"
#include "src/__support/macros/config.h"
namespace LIBC_NAMESPACE_DECL {
namespace cpp {
-/// A function type adapted from LLVM's function_ref.
+/// A non-owning reference to a callable, similar to C++26 std::function_ref.
/// This class does not own the callable, so it is not in general safe to
-/// store a function.
-template <typename Fn> class function;
+/// store a function_ref.
+template <typename Fn> class function_ref;
-template <typename Ret, typename... Params> class function<Ret(Params...)> {
- Ret (*callback)(intptr_t callable, Params... params) = nullptr;
+template <typename Ret, typename... Params> class function_ref<Ret(Params...)> {
+ Ret (*callback)(intptr_t callable, Params... params);
intptr_t callable;
template <typename Callable>
LIBC_INLINE static Ret callback_fn(intptr_t callable, Params... params) {
- return (*reinterpret_cast<Callable *>(callable))(
- cpp::forward<Params>(params)...);
+ // Discard the result if Ret is void, and convert it implicitly otherwise.
+ // Avoiding an explicit cast lets the compiler diagnose narrowing
+ // conversions and discarded [[nodiscard]] results.
+ if constexpr (cpp::is_void_v<Ret>)
+ (*reinterpret_cast<Callable *>(callable))(
----------------
kaladron wrote:
(optional nit) Both the if and else have to do this cast. This could be pulled up to a temporary to make those a bit easier to read.
https://github.com/llvm/llvm-project/pull/236108
More information about the libc-commits
mailing list