1// -*- C++ -*-
2//===----------------------------------------------------------------------===//
3//
4// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
5// See https://llvm.org/LICENSE.txt for license information.
6// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
7//
8//===----------------------------------------------------------------------===//
9
10#ifndef _LIBCPP___FUNCTIONAL_INVOKE_H
11#define _LIBCPP___FUNCTIONAL_INVOKE_H
12
13#include <__config>
14#include <__type_traits/invoke.h>
15#include <__type_traits/is_void.h>
16#include <__utility/forward.h>
17
18#if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER)
19# pragma GCC system_header
20#endif
21
22#if _LIBCPP_STD_VER >= 17
23
24_LIBCPP_BEGIN_NAMESPACE_STD
25
26# if __has_builtin(__builtin_invoke)
27
28template <class... _Args>
29_LIBCPP_CONSTEXPR_SINCE_CXX20 __direct_invoke_result_t<_Args...> invoke(_Args&&... __args)
30 _NOEXCEPT_(noexcept(__builtin_invoke(static_cast<_Args&&>(__args)...))) {
31 return __builtin_invoke(static_cast<_Args&&>(__args)...);
32}
33
34# else
35
36template <class _Fn, class... _Args>
37_LIBCPP_CONSTEXPR_SINCE_CXX20 invoke_result_t<_Fn, _Args...>
38invoke(_Fn&& __f, _Args&&... __args) noexcept(is_nothrow_invocable_v<_Fn, _Args...>) {
39 return std::__invoke(std::forward<_Fn>(__f), std::forward<_Args>(__args)...);
40}
41
42# endif
43
44# if _LIBCPP_STD_VER >= 23
45template <class _Result, class _Fn, class... _Args>
46 requires is_invocable_r_v<_Result, _Fn, _Args...>
47constexpr _Result invoke_r(_Fn&& __f, _Args&&... __args) noexcept(is_nothrow_invocable_r_v<_Result, _Fn, _Args...>) {
48 if constexpr (is_void_v<_Result>) {
49 static_cast<void>(std::invoke(std::forward<_Fn>(__f), std::forward<_Args>(__args)...));
50 } else {
51 // TODO: Use reference_converts_from_temporary_v once implemented
52 // using _ImplicitInvokeResult = invoke_result_t<_Fn, _Args...>;
53 // static_assert(!reference_converts_from_temporary_v<_Result, _ImplicitInvokeResult>,
54 static_assert(true,
55 "Returning from invoke_r would bind a temporary object to the reference return type, "
56 "which would result in a dangling reference.");
57 return std::invoke(std::forward<_Fn>(__f), std::forward<_Args>(__args)...);
58 }
59}
60# endif
61
62_LIBCPP_END_NAMESPACE_STD
63
64#endif // _LIBCPP_STD_VER >= 17
65
66#endif // _LIBCPP___FUNCTIONAL_INVOKE_H
67