std::invoke (3) Linux Manual Page
std::invoke – std::invoke
Synopsis
Defined in header <functional>
template< class F, class... Args> (since C++17)
std::invoke_result_t<F, Args...> invoke(F&& f, Args&&... args) noexcept(/* see below */);
Invoke the Callable object f with the parameters args. As by INVOKE(std::forward<F>(f), std::forward<Args>(args)…).
where INVOKE(f, t1, t2, …, tN) is defined as follows:
* If f is a pointer_to_member_function of class T:
* Otherwise, if N == 1 and f is a pointer_to_data_member of class T:
* 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
Exceptions
noexcept specification:
noexcept(std::is_nothrow_invocable_v<F, Args…>)
Possible implementation
Example
// Run this code
#include <functional>
#include <iostream>
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);
}
Output:
See also
mem_fn creates a function object out of a pointer to a member
(C++11)
result_of
invoke_result deduces the result type of invoking a callable object with a set of arguments
(C++11)(removed in C++20)
(C++17)
is_invocable
is_invocable_r checks if a type can be invoked (as if by std::invoke) with the given argument types
is_nothrow_invocable (class template)
is_nothrow_invocable_r
(C++17)
apply calls a function with a tuple of arguments
(C++17)
