Search code examples
c++stdbind

"inverse" bind by discarding parameters in c++


std::bind reduces the number of parameters a function takes by setting the remaining parameters to preset values. Is there also a function which increases the number of parameters by discarding them?

For example, to make a function taking an int from function of type function<void()>, one could do this using a lambda, like this:

[=](int){function();}

So it is easy to do without helper functions, but the same is true for std::bind.

Is there something in the standard to do this?

Why I am asking this

I could use

[](){function(3);}

To bind 3 to the parameter of function. But I find this code less readable (at least for people who know bind). The moment I use bind, my intentions are clear. And I wonder if this can also be true for an "inverse" bind.


Solution

  • Your premise is wrong. The purpose of bind is not to reduce the number of parameters. The number of call parameters of the bind expression is essentially unrelated to the number of parameters of the bound function. In fact, you can call a bind expression with an arbitrary number of arguments (but at least as many as there are placeholders).

    For example, consider:

    int f(int, int);
    
    auto g = std::bind(f, std::bind(f, _1, _2), std::bind(f, _2, _3));
    

    This defines g(x, y, z) := f(f(x, y), f(y, z)).