When to use std::invoke instead of simply calling the invokable?

If the invocable is a pointer to a member function, then you need to do one of these:

(arg1->*f)(arg2,...);
(arg1.*f)(arg2,...);

Depending on what arg1 is.

INVOKE (and its official library counterpart std::invoke) was pretty much designed to simplify such messes.

You'd use std::invoke to support the caller of your code passing any callable, and not having to adapt their call site with a lambda or a call to std::bind.


std::invoke can be useful when you create a lambda and need to call it immediately. It the lambda is big, parentheses after it can be hard to observe:

[] (/* args */) {
    // many lines here
    // ...
} (/* args */)

vs

std::invoke(
    [] (/* args */) {
        // many lines here
        // ...
    },
    /* args */);

Tags:

C++

C++17

Std