The 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.
To use std::function
it is necessary to include the header: <functional>
.
The most basic usage would be the example below:
In this case it stores the
square
function without having to inform the parameters, in this case it takes anint
inside the parentheses and returns anint
inside theangle brackets
.
In this case it stores two int
and returns a double
:
Similar to above, but now it’s a function pointer to the address of &sum
:
In the <functional>
header is also available std::negate
, in this case using std::negate
it inverts the output value:
Output:
-42
.
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.