2010-07-23 54 views
7
#include <iostream> 
#include <string> 

#include <boost/bind.hpp> 

void foo(std::string const& dummy) 
{ 
    std::cout << "Yo: " << dummy << std::endl; 
} 

int main() 
{ 
    int* test; 
    std::string bar("platypus"); 
    (boost::bind(&foo, bar))(test, test, test, test, test, test, test, test); 
} 

運行時會打印出「Yo:platypus」。它似乎完全忽略了額外的參數。我希望得到一個編譯錯誤。我不小心通過這種方式在我的代碼中引入了一個錯誤。爲什麼使用額外的參數可以調用Boost.Bind函數?

回答

2

我不知道爲什麼這是允許的,但我知道它是預期的行爲。從here

綁定能夠處理的功能具有更多 比兩個參數,和它的參數 替換機制是更 一般:

bind(f, _2, _1)(x, y);     // f(y, x) 
bind(g, _1, 9, _1)(x);     // g(x, 9, x) 
bind(g, _3, _3, _3)(x, y, z);   // g(z, z, z) 
bind(g, _1, _1, _1)(x, y, z);   // g(x, x, x) 

注意的是,在最後一個例子中, 函數對象(g, _1,_1,_1)不包含任何超出 的參數的引用,但它仍可以與多個參數一起使用 。 任何額外的 自變量被忽略忽略在第三個例子(強調我的),只是 像第一個和第二個參數 被忽略。

+0

我仍然很想知道爲什麼允許這種行爲,如果任何人發現的原因:) – 2010-07-31 21:26:43

+0

@約瑟夫:可能太複雜,明確禁止它。 – 2011-07-04 11:53:00

0

我敢打賭,它創造了一個可變函數的邊界函數,如printf

+1

沒有。參數計數具有固定的[實現定義限制](http://www.boost.org/doc/libs/1_43_0/libs/bind/bind.html#NumberOfArguments)。目前的限制是九。 – 2010-07-23 18:29:19

相關問題