本文介绍了为什么std :: bind可以分配给参数不匹配的std :: function?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的代码如下:

  #include< functional> 
#include< iostream>
使用namespace std;
void F(int x){
cout<< x<< ENDL;
}
int main(){
std :: function< void(int)> f1 = std :: bind(F,std :: placeholders :: _ 1);
f1(100); //这个工程,会打印100.

int x = 0;
std :: function< void()> f2 = std :: bind(F,x);
f2(); //这个工作,将打印0.

std :: function< void(int)> f3 = std :: bind(F,x);
f3(200); //但为什么这项工作??????它打印0.
return 0;

$ / code>

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

解决方案

这是正确的行为。



std :: bind 需要这个松动
$ b

考虑 std ::占位符,它用于标记参数通过传递给绑定函数。

 使用std :: placeholders; 
std :: function< void(int)> f2 = std :: bind(F,_1);
//参数1传递给^^
//绑定函数。

f2(7); // int 7传递给F

类似的,有 _2 为第二个参数, _3 为第三个参数,依此类推。



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

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

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

  f3(10,20,30); // int 30传递给F.其余的?忽略。 

所以这是预期的行为,可能是唯一的特征 std :: b

std生成的对象std :: bind 旨在接受并忽略任何多余的参数。


I have code as follows:

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

My compiler info is:Apple LLVM version 6.0 (clang-600.0.56) (based on LLVM 3.5svn)Target: x86_64-apple-darwin13.4.0Thread model: posix

解决方案

That is correct behavior.

std::bind needs this looseness to fit its own specification.

Consider std::placeholders, which is used to mark parameters that are passed through to the bound function.

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

Similarly, there is _2 for the second parameter, _3 for the third, and so on.

That brings up an interesting question. How should this function object behave?

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

As you might imagine, it follows its own promise to pass the third parameter to F. Which means it does nothing to the first two parameters.

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

So this is expected behavior, and possibly the only "feature" that std::bind holds over lambdas, even in C++14.

The object produced by std::bind is designed to accept and ignore any extraneous parameters.

这篇关于为什么std :: bind可以分配给参数不匹配的std :: function?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-30 22:59