Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

std

c++17

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, ...);
like image 989
Elad Weiss Avatar asked Sep 24 '17 09:09

Elad Weiss


People also ask

When to use std:: invoke?

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 .

What is invoke in CPP?

std::invoke( f, args... ) is a slight generalization of typing f(args...) that also handles a few additional cases. Something callable includes a function pointer or reference, a member function pointer, an object with an operator() , or a pointer to member data.


2 Answers

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.

like image 74
StoryTeller - Unslander Monica Avatar answered Oct 17 '22 21:10

StoryTeller - Unslander Monica


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 */);
like image 28
Dev Null Avatar answered Oct 17 '22 21:10

Dev Null