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, ...);
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( 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.
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 */);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With