views:

133

answers:

2

hi,

I have just been working with boost::bind and boost::function and noticed the following behaviour (which I thought was a bit odd). You can bind a function with fewer parameters than required by the boost::function type! It appears as though any additional parameters are simply ignored and just fall away.

So why is this behaviour correct? My expectation would be that a compile error should be raised stating the incompatibility.

See below for working code example that shows the issue

#include "boost/bind.hpp"
#include "boost/function.hpp"

namespace
{
  int binder(const char& testChar, 
             const int& testInt, 
             const std::string& testString)
  {
    return 3;
  }

}

int main(int c, char** argv)
{
  boost::function<int(const char&, 
                      const int&, 
                      const std::string&, 
                      const float&, 
                      const std::string&, 
                      const int&)> test;
  test = boost::bind(&::binder, _1, _2, _3);

  std::cout << test('c', 1, "something", 1.f, "more", 10) << std::endl;

}
+6  A: 

Isn't this the point of boost::bind - to allow you to remap the prototype of the function? You're making test be usable with 6 input parameters where your underlying function needs only 3.

This page: http://blog.think-async.com/2010/04/bind-illustrated.html has a really good overview of how boost::bind works.

Edric
I guess I am surprised that it does this implicitly, since it is very picky about function signatures in all other circumstances. I understand boost::bind quite well already and I just never saw this as a use case.
radman
@radman I'm with you. I think I would almost prefer that boost cause errors to be generated in this case. I find it more disturbing than a convenience.
Omnifarious
A: 

It is a paradigm from functional programming, currying: http://en.wikipedia.org/wiki/Currying meaning that you transform a function taking more than 0 parameters into a function taking less parameters, with those you supplied filled in to be constant; the values you supplied.

E.g. using bind/currying you are able to do this:

// takes 2 arguments
function multiply(x,y) { return x*y; }

// make shorthand for multiply-by-two
function mult_by_two(x) =  multiply(x, 2)

h.

haavee
sorry but the question is in the other direction, where you bind a method taking n parameters into a method taking n+x parameters. I was already well aware of what you are describing, thanks for the answer though.
radman
one of these days I should learn to read I guess ;) sorry! nonetheless ... it is not all that different right? You can supply any old C function with more arguments than it actually uses, as long as - *at the call site* - the prototype )
haavee