What is std :: invoke in c ++?

I just read about std::thread and std::bind , which I came across with the concept of Callable and std::invoke .

I read about std::invoke in cppreference , but I did not understand what he said. Here is my question:
What is std::invoke , std::function , std::bind and the Callable concept? And what is the relationship between them?

+7
c ++ c ++ 17
source share
2 answers

std::invoke takes something called and arguments to call it, and makes the call. std::invoke( f, args... ) is a small generalization of the input f(args...) , which also handles several additional cases.

Something called includes a pointer to a function or reference, a pointer to a member function, an object with operator() or a pointer to the data of an element.

In member cases, the first argument is interpreted as this . Then the remaining arguments are passed to () (except in the case of a pointer-member-data-member).

INVOKE was a concept in the C ++ standard; C ++ 17 just exposes std::invoke , which does this directly. I suspect it was open because it was useful in other metaprogramming, partly because each standard library already has an INVOKE implementation, and exposing it was mostly free, and partly because it made it easier to talk about INVOKE when this is a specific thing.

+10
source share

A Callable , besides the C ++ specs, is "something that can be called." This should not be a function: C ++ has several types that can be called, and every time they can appear (read: common code), this is problematic and too repeatable.

Why std::invoke - this - allows you to call a common object that can be called (which, according to C ++ 17, satisfies the concept of Callable ), can be activated without much effort.

Consider a simple example:

 void foo() { std::cout << "hello world\n"; }; template <bool b> struct optionally_callable { std::enable_if_t<b> operator() () { std::cout << "hi again\n"; } }; int main() { auto c = [] { std::cout << "hi from lambda\n" ;}; std::invoke(foo); std::invoke(c); auto o = optionally_callable<true>{}; //auto o2 = optionally_callable<false>{}; std::invoke(o); } 

o2 not , i.e. std::is_invocable<decltype(o2)>::value false .

+2
source share

All Articles