我什么时候应该使用std :: bind?

gnz*_*lbg 36 c++ lambda bind standard-library c++11

每次我需要使用时std::bind,我最终都会使用lambda.那么我std::bind什么时候应该使用?我刚刚从一个代码库中删除它,我发现lambdas总是更简单,更清晰std::bind.是不是std::bind完全没必要?它不应该在将来被弃用吗?我std::bind什么时候应该更喜欢lambda函数?(必须有一个原因,它与lambda一起进入标准.)

我也注意到越来越多的人熟悉lambdas(所以他们知道lambdas做了什么).但是,很少有人熟悉std::bindstd::placeholders.

Nic*_*las 30

这是lambda无法做到的事情:

std::unique_ptr<SomeType> ptr = ...;
return std::bind(&SomeType::Function, std::move(ptr), _1, _2);
Run Code Online (Sandbox Code Playgroud)

Lambdas无法捕获仅移动类型; 它们只能通过复制或左值引用来捕获值.虽然这是一个暂时的问题,正在积极解决C++ 14;)

"更简单,更清晰"是一个意见问题.对于简单的绑定案例,bind可以减少打字.bind也只关注功能绑定,所以如果你看到std::bind,你知道你在看什么.然而,如果您使用lambda,则必须查看lambda实现以确定它的作用.

最后,C++不会因为某些其他功能可以执行的操作而弃用.auto_ptr被弃用,因为它本身就很危险,而且有一个非危险的选择.

  • C++ - 14将解决lambdas的这种缺陷. (5认同)
  • +1.[Scott Meyers即将出版的书"Effective C++ 11"中似乎有一个项目](http://scottmeyers.blogspot.cz/2013/01/effective-c11-content-and-status.html):"*首选lambdas为`std :: bind`*".我没有足够的洞察力对此发表评论,但如果可以,那就太好了. (4认同)
  • @AndyProwl最适用的是你引用的书中的这个简短引用:"...从C++ 14开始,[std :: bind]没有很好的用例" (4认同)

Jon*_*ely 23

您可以std::bind使用lambdas 创建多态对象,即std::bind可以使用不同的参数类型调用返回的调用包装器:

#include <functional>
#include <string>
#include <iostream>

struct Polly
{
  template<typename T, typename U>
    auto operator()(T t, U u) const -> decltype(t + u)
    { return t + u; }
};

int main()
{
  auto polly = std::bind(Polly(), std::placeholders::_1, "confusing");

  std::cout << polly(4) << polly(std::string(" this is ")) << std::endl;    
}
Run Code Online (Sandbox Code Playgroud)

我创建这个拼图不是一个好的代码的例子,但它确实展示了多态调用包装器.

  • 是的,在C++ 14中,这相当于绑定表达式:`[p = Polly {}](auto t){return p(t,"confusing"); }` (13认同)
  • c ++ 14泛型lambda解决了这个问题吗? (2认同)