Reputation: 51
Consider some easy code below:
int f1(int a) {
std::cout << a << std::endl;
}
int main (int agrc, char* argv[]) {
std::function<int(int)> f = std::bind(&f1, std::placeholders::_1);
f(123);
return 0;
}
I've read some documents about std::function and std::bind, but still don't understand how does it work.
The compiler shows that call of std::bind returns an object of type _Bind_helper, however, I don't see the std::function class has a construction function with input type _Bind_helper, so how does the std::function xxx = std::bind xxx work?
Upvotes: 3
Views: 1357
Reputation: 6474
According to ccpreference.com:
Class template
std::function
is a general-purpose polymorphic function wrapper. Instances ofstd::function
can store, copy, and invoke any Callable target -- functions, lambda expressions, bind expressions, or other function objects, as well as pointers to member functions and pointers to data members.The stored callable object is called the target of std::function. If a
std::function
contains no target, it is called empty. Invoking the target of an empty std::function results instd::bad_function_call
exception being thrown.std::function satisfies the requirements of CopyConstructible and CopyAssignable.
std::function
is basically a wrapper around a callable object. It's known as a type erasure object - it erases the details of operations to provide a common interface.
Your std::bind
expression
std::bind(&f1, std::placeholders::_1)
produces a function object that calls the function f1
with a parameter that you provide in a placeholder and the return type is int
. Hence you can assign that to a function object with the same signature:
std::function<int(int)>
which uses a constructor that take a callable object.
Upvotes: 1
Reputation: 238311
I don't see the std::function class has a construction function with input type _Bind_helper, so how does the std::function xxx = std::bind xxx work?
It does have such constructor. It's this one:
template< class F >
function( F f );
Note that this converting constructor participates in overload resolution only if the (deduced) template argument is a Callable - which the return type of std::bind
is.
Upvotes: 3