[英]Why can a Boost.Bind function be called with extra parameters?
#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”。 它似乎完全忽略了額外的參數。 我希望得到一個編譯錯誤。 我不小心以這種方式向我的代碼中引入了一個錯誤。
我不知道為什么這是允許的,但我確實知道這是預期的行為。 從這里 :
bind可以處理具有兩個以上參數的函數,其參數替換機制更通用:
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)
請注意,在最后一個示例中,bind(g,_1,_1,_1)生成的函數對象不包含對第一個參數之外的任何參數的引用,但它仍可以與多個參數一起使用。 任何額外的參數都會被默默忽略 (強調我的),就像在第三個例子中忽略第一個和第二個參數一樣。
我敢打賭它正在創建綁定函數作為可變參數函數,如printf
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.