std::invoke, std::invoke_r

From cppreference.com
< cpp‎ | utility‎ | functional
 
 
Utilities library
General utilities
Date and time
Function objects
Formatting library (C++20)
(C++11)
Relational operators (deprecated in C++20)
Integer comparison functions
(C++20)(C++20)(C++20)   
(C++20)
Swap and type operations
(C++14)
(C++11)
(C++11)
(C++11)
(C++17)
Common vocabulary types
(C++11)
(C++17)
(C++17)
(C++17)
(C++11)
(C++17)
(C++23)
Elementary string conversions
(C++17)
(C++17)
 
Function objects
Function wrappers
(C++11)
(C++11)
Partial function application
(C++20)(C++23)
(C++11)
Function invocation
invokeinvoke_r
(C++17)(C++23)
Identity function object
(C++20)
Reference wrappers
(C++11)(C++11)
Transparent operator wrappers
(C++14)
(C++14)
(C++14)
(C++14)
(C++14)
(C++14)
(C++14)
(C++14)
(C++14)
(C++14)
(C++14)
(C++14)
Negators
(C++17)
Searchers
Constrained comparators
Old binders and adaptors
(until C++17)
(until C++17)
(until C++17)
(until C++17)
(until C++17)(until C++17)(until C++17)(until C++17)
(until C++20)
(until C++20)
(until C++17)(until C++17)
(until C++17)(until C++17)

(until C++17)
(until C++17)(until C++17)(until C++17)(until C++17)
(until C++20)
(until C++20)
 
Defined in header <functional>
(1)
template< class F, class... Args >

std::invoke_result_t<F, Args...>

  invoke( F&& f, Args&&... args ) noexcept(/* see below */);
(since C++17)
(until C++20)
template< class F, class... Args >

constexpr std::invoke_result_t<F, Args...>

  invoke( F&& f, Args&&... args ) noexcept(/* see below */);
(since C++20)
template< class R, class F, class... Args >
constexpr R invoke_r( F&& f, Args&&... args ) noexcept(/* see below */);
(2) (since C++23)
1) Invoke the Callable object f with the parameters args. As by INVOKE(std::forward<F>(f), std::forward<Args>(args)...). This overload participates in overload resolution only if std::is_invocable_v<F, Args...> is true.
2) Same as (1), except that the result is implicitly converted to R if R is not possibly cv-qualified void, or discarded otherwise. This overload participates in overload resolution only if std::is_invocable_r_v<R, F, Args...> is true.

The operation INVOKE(f, t1, t2, ..., tN) is defined as follows:

  • If std::is_base_of<T, std::decay_t<decltype(t1)>>::value is true, then INVOKE(f, t1, t2, ..., tN) is equivalent to (t1.*f)(t2, ..., tN)
  • If std::decay_t<decltype(t1)> is a specialization of std::reference_wrapper, then INVOKE(f, t1, t2, ..., tN) is equivalent to (t1.get().*f)(t2, ..., tN)
  • If t1 does not satisfy the previous items, then INVOKE(f, t1, t2, ..., tN) is equivalent to ((*t1).*f)(t2, ..., tN).
  • If std::is_base_of<T, std::decay_t<decltype(t1)>>::value is true, then INVOKE(f, t1) is equivalent to t1.*f
  • If std::decay_t<decltype(t1)> is a specialization of std::reference_wrapper, then INVOKE(f, t1) is equivalent to t1.get().*f
  • If t1 does not satisfy the previous items, then INVOKE(f, t1) is equivalent to (*t1).*f
  • Otherwise, INVOKE(f, t1, t2, ..., tN) is equivalent to f(t1, t2, ..., tN) (that is, f is a FunctionObject)

Parameters

f - Callable object to be invoked
args - arguments to pass to f

Return value

1) The value returned by f.
2) The value returned by f, implicitly converted to R, if R is not void. None otherwise.

Exceptions

1)
noexcept specification:  
noexcept(std::is_nothrow_invocable_v<F, Args...>)
2)
noexcept specification:  
noexcept(std::is_nothrow_invocable_r_v<R, F, Args...>)

Possible implementation

First version
namespace detail {
template<class>
constexpr bool is_reference_wrapper_v = false;
template<class U>
constexpr bool is_reference_wrapper_v<std::reference_wrapper<U>> = true;
 
template<class C, class Pointed, class T1, class... Args>
constexpr decltype(auto) invoke_memptr(Pointed C::* f, T1&& t1, Args&&... args)
{
    if constexpr (std::is_function_v<Pointed>) {
        if constexpr (std::is_base_of_v<C, std::decay_t<T1>>)
            return (std::forward<T1>(t1).*f)(std::forward<Args>(args)...);
        else if constexpr (is_reference_wrapper_v<std::decay_t<T1>>)
            return (t1.get().*f)(std::forward<Args>(args)...);
        else
            return ((*std::forward<T1>(t1)).*f)(std::forward<Args>(args)...);
    } else {
        static_assert(std::is_object_v<Pointed> && sizeof...(args) == 0);
        if constexpr (std::is_base_of_v<C, std::decay_t<T1>>)
            return std::forward<T1>(t1).*f;
        else if constexpr (is_reference_wrapper_v<std::decay_t<T1>>)
            return t1.get().*f;
        else
            return (*std::forward<T1>(t1)).*f;
    }
}
} // namespace detail
 
template<class F, class... Args>
constexpr std::invoke_result_t<F, Args...> invoke(F&& f, Args&&... args) 
    noexcept(std::is_nothrow_invocable_v<F, Args...>)
{
    if constexpr (std::is_member_pointer_v<std::decay_t<F>>)
        return detail::invoke_memptr(f, std::forward<Args>(args)...);
    else
        return std::forward<F>(f)(std::forward<Args>(args)...);
}
Second version
template<class R, class F, class... Args>
    requires std::is_invocable_r_v<R, F, Args...>
constexpr R invoke_r(F&& f, Args&&... args) 
    noexcept(std::is_nothrow_invocable_r_v<R, F, Args...>)
{
    if constexpr (std::is_void_v<R>)
        std::invoke(std::forward<F>(f), std::forward<Args>(args)...);
    else
        return std::invoke(std::forward<F>(f), std::forward<Args>(args)...);
}

Notes

Feature-test macro: __cpp_lib_invoke (for std::invoke)
Feature-test macro: __cpp_lib_invoke_r (for std::invoke_r)

Example

#include <functional>
#include <iostream>
#include <type_traits>
 
struct Foo {
    Foo(int num) : num_(num) {}
    void print_add(int i) const { std::cout << num_+i << '\n'; }
    int num_;
};
 
void print_num(int i)
{
    std::cout << i << '\n';
}
 
struct PrintNum {
    void operator()(int i) const
    {
        std::cout << i << '\n';
    }
};
 
int main()
{
    // invoke a free function
    std::invoke(print_num, -9);
 
    // invoke a lambda
    std::invoke([]() { print_num(42); });
 
    // invoke a member function
    const Foo foo(314159);
    std::invoke(&Foo::print_add, foo, 1);
 
    // invoke (access) a data member
    std::cout << "num_: " << std::invoke(&Foo::num_, foo) << '\n';
 
    // invoke a function object
    std::invoke(PrintNum(), 18);
 
#   if defined(__cpp_lib_invoke_r)
    auto add = [](int x, int y) { return x + y; };
    auto ret = std::invoke_r<float>(add, 11, 22);
    static_assert(std::is_same<decltype(ret), float>());
    std::cout << ret << '\n';
    std::invoke_r<void>(print_num, 44);
#   endif
}

Possible output:

-9
42
314160
num_: 314159
18
33
44

See also

(C++11)
creates a function object out of a pointer to a member
(function template)
(C++11)(removed in C++20)(C++17)
deduces the result type of invoking a callable object with a set of arguments
(class template)
checks if a type can be invoked (as if by std::invoke) with the given argument types
(class template)
(C++17)
calls a function with a tuple of arguments
(function template)