C++ 11 std::function和std::bind使用详解

2020-02-20 12:01:05王旭

function还可以作为函数入参,这样可以在函数外部控制函数的内部行为了,让我们的函数变得更加灵活。

void Foo(int x, std::function<void(int)>& f)
{
  if(x%2==0)
  f(x);
}

void G(int x)
{
  cout<<x<<endl;
}

void H(int x)
{
  cout<<x+2<<endl;
}

void TestFoo()
{
  auto f = std::bind(G, std::placeholders::_1); 
  Foo(4, f);

  //在Foo函数外面更改f的行为
  f = std::bind(H, std::placeholders::_1);
  Foo(4, f);
}

c++11中推出function是为了泛化函数对象,函数指针,引用函数,成员函数的指针,让我们可以按更统一的方式写出更加泛化的代码;推出bind是为了替换和增强之前标准库的bind1st和bind2st,让我们的用起来更方便

 到此这篇关于C++ 11 std::function和std::bind使用详解的文章就介绍到这了,更多相关C++ 11 std::function和std::bind内容请搜素易采站长站以前的文章或下面相关文章,希望大家以后多多支持易采站长站!