为什么std :: bind可以分配给参数不匹配的std :: function?

时间:2015-03-20 03:53:44

标签: c++ function c++11 bind std

我的代码如下:

#include <functional>
#include <iostream>
using namespace std;
void F(int x) {
  cout << x << endl;
}
int main() {
  std::function<void(int)> f1 = std::bind(F, std::placeholders::_1);
  f1(100);  // This works, will print 100.

  int x = 0;
  std::function<void()> f2 = std::bind(F, x);
  f2();  // This works, will print 0.

  std::function<void(int)> f3 = std::bind(F, x);
  f3(200);  // BUT WHY THIS WORKS?????? It prints 0.
  return 0;
}

我的编译器信息是: Apple LLVM 6.0版(clang-600.0.56)(基于LLVM 3.5svn) 目标:x86_64-apple-darwin13.4.0 线程模型:posix

1 个答案:

答案 0 :(得分:21)

这是正确的行为。

std::bind需要此松散以符合自己的规范。

考虑std::placeholders,它用于标记传递给绑定函数的参数。

using std::placeholders;
std::function<void(int)> f2 = std::bind( F, _1 );
//  Parameter 1 is passed to                ^^
//  the bound function.

f2(7); // The int 7 is passed on to F

同样,第二个参数_2,第三个参数_3,依此类推。

这提出了一个有趣的问题。该函数对象应该如何表现?

auto f3 = std::bind( F, _3 );

正如您可能想象的那样,它遵循自己的承诺将第三个参数传递给F.这意味着它对前两个参数没有任何作用。

f3(10, 20, 30); // The int 30 is passed on to F. The rest?  Ignored.

所以这是预期的行为,可能是唯一的&#34;功能&#34; std::bind支持lambda,即使在C ++ 14和C ++ 17中也是如此。

std::bind生成的对象旨在接受和忽略任何无关的参数。

相关问题