Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / C++

std::invoke: uniform callable invocation

std::invoke calls functions, function objects, and member pointers through one perfect-forwarding interface.

Version: C++23

Syntax

template<class F, class... Args>
constexpr std::invoke_result_t<F, Args...>
std::invoke(F&& callable, Args&&... args)
    noexcept(std::is_nothrow_invocable_v<F, Args...>);

std::invoke(f,args...) implements INVOKE: an ordinary callable receives the forwarded arguments; a member-function pointer needs an object, pointer, or std::reference_wrapper; a data-member pointer yields the corresponding member. The function participates only when std::is_invocable_v<F,Args...> is true.

The example invokes Counter::add, reads Counter::base, and calls a lambda, so it prints 12 7 12. Value categories and constness are forwarded through std::forward, and member-data access can therefore return a reference.

The result type is std::invoke_result_t<F,Args...> and conditional noexcept matches std::is_nothrow_invocable_v. A callable exception propagates. An incompatible member receiver makes std::is_invocable_v false and the std::invoke overload unavailable; undefined behavior instead comes from accessing through an otherwise compatible but null or dangling pointer or reference. The object and referenced arguments must live through the call; std::invoke neither defers work nor manages their lifetimes.

Examples

#include <functional>
#include <iostream>

struct Counter {
    int base;
    int add(int value) const { return base + value; }
};

int main() {
    const Counter counter{7};
    std::cout << std::invoke(&Counter::add, counter, 5) << ' '
              << std::invoke(&Counter::base, counter) << ' '
              << std::invoke([](int a, int b) { return a * b; }, 3, 4) << '\n';
}

Result

12 7 12

std::invoke → 12 7 12

Sources