简体   繁体   中英

std::function and std::bind behavior

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)

How it's possible to call void() function by using void(int) functor?

std::bind(fun) does not return a void() function, it returns a call wrapper of unspecified type.

The usual way to invoke that call wrapper would be with zero arguments, but in most implementations of bind() that type can be called with zero or more arguments and the additional arguments will be ignored (ie not passed to the target function)

More generally, for a function F taking N arguments, bind(F) returns a call wrapper that can be called with N or more arguments. If you bind arguments or use placeholders then it will alter the minimum number of arguments needed to invoke the call wrapper.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM