2010-06-21 107 views
2

我刚刚与boost::bindboost::function一起工作,并注意到以下行为(我认为这有点奇怪)。您可以使用比boost :: function类型所需的参数更少的参数来绑定一个函数!看起来似乎任何附加的参数都被忽略,并且会消失。这为什么有效?

那么为什么这种行为是正确的?我的期望是应该提出编译错误,说明不兼容性。

请参阅以下工作代码示例,说明问题

#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; 

} 
+0

我不确定这是否是“正常”,但我想是的。 'Qt'信号和插槽也可以。 – ereOn 2010-06-21 07:18:21

回答

6

这难道不是boost::bind点 - 让您重新映射函数的原型?您正在使test可与6个输入参数一起使用,其中您的底层功能只需要3个。

本页面:http://blog.think-async.com/2010/04/bind-illustrated.htmlboost::bind的工作原理有很好的概述。

+1

我想我很惊讶它隐含地这样做,因为它在所有其他情况下对函数签名非常挑剔。我已经很好地理解boost :: bind了,我从来没有把它看作是一个用例。 – radman 2010-06-21 07:42:42

+2

@radman我和你在一起。我想我会更喜欢在这种情况下产生错误。我觉得它比方便更令人不安。 – Omnifarious 2010-06-22 00:13:04

0

这是一个函数式编程的范例,currying:http://en.wikipedia.org/wiki/Currying这意味着你可以将一个函数的参数多于0的函数转换成一个函数参数较少的函数,填充的参数为常量;您提供的值。

E.g.使用绑定/ currying你能够这样做:

// 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

抱歉,但问题是在另一个方向,你绑定一个方法采取n参数到一个方法采取n + x参数。我已经很清楚你在描述什么,谢谢你的回答。 – radman 2010-06-21 11:09:01

+0

这些天我应该学会阅读我猜);对不起!尽管如此......这不是完全不同的权利?只要 - *在调用站点* - 原型和参数个数相匹配,您可以提供比实际使用的参数更多的旧C函数。 main()是一个非常好的例子;) – haavee 2010-06-21 11:15:53