I have this code:
#include <iostream>
#include <functional>
#include <vector>
void fun()
{
std::cout<<"fun";
}
void gun(int)
{
std::cout<<"gun";
}
int main()
{
std::vector<std::function<void(int)>> vec;
vec.push_back(std::bind(fun));
vec.push_back(gun);
vec[0](1);
vec[1](2);
}
Can you please explain how it's possible for std::bind
to return std::function<void(int)>
when binding void()
function?
How it's possible to call void()
function by using void(int)
functor?
The signature passed as the template argument for function
only determines how many place holders (_1
) will be bound, and as what types.
The invocation of the actual function only uses the number of arguments actually required by the bound function. In effect, the superfluous parameter is ignored.
Another, more enlightening (?) example, looking at this from the other side:
#include <iostream>
#include <functional>
void gun(int i)
{
std::cout<<"gun("<<i<<")";
}
int main()
{
using namespace std::placeholders;
std::bind(gun, _5)("ignore", 3, "and", 4, 43);
}
Prints
gun(43)
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