How to Use std::function in C++
A general purpose polymorphic function wrapper.
std::function class template is a general purpose polymorphic function wrapper. Instances of
std::function can store, copy and invoke any target: lambda expressions, binding expressions or other function objects, as well as pointers to member functions and pointers to data members.
std::function is a type of disposal object. This means that it erases the details of how some operations happen and provides a uniform runtime interface for them.
std::function it is necessary to include the header:
The most basic usage would be the example below:
In this case it stores the
squarefunction without having to inform the parameters, in this case it takes an
intinside the parentheses and returns an
In this case it stores two
int and returns a
Similar to above, but now it’s a function pointer to the address of
<functional> header is also available
std::negate, in this case using
std::negate it inverts the output value:
It can also be used in conjunction with lambda, so its signature makes it possible to identify the lambda:
That is, it is another STL feature that can be useful in several cases where performance is fundamental, but debugging is also important. For more information see this link.