Search code examples
c++stdc++17

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


As I understand, std::invoke allows me to do something like:

std::invoke(f, arg1, arg2, ...);

Is there a scenario when it's more advantageous than simply doing:

f(arg1, arg2, ...);

Solution

  • 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.