Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

std::function and std::bind behavior

Tags:

c++

c++11

stl

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?

like image 629
Mircea Ispas Avatar asked Apr 23 '13 06:04

Mircea Ispas


1 Answers

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)
like image 92
sehe Avatar answered Sep 28 '22 08:09

sehe