开发者

Why does this work?

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& te开发者_JS百科stChar, 
             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;

}


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜