39

每次我需要使用std::bind时,我最终都会使用 lambda。那么我应该什么时候使用std::bind呢?我刚刚从一个代码库中删除了它,我发现 lambdas 总是比std::bind. 不是std::bind完全没有必要吗?将来不应该弃用吗?我什么时候应该更喜欢std::bindlambda 函数?(它与 lambdas 同时进入标准肯定是有原因的。)

我还注意到越来越多的人熟悉 lambda(所以他们知道 lambda 的作用)。但是,熟悉std::bind和的人要少得多std::placeholders

4

2 回答 2

32

Here's something you can't do with a lambda:

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

Lambdas can't capture move-only types; they can only capture values by copy or by lvalue reference. Though admittedly this is a temporary issue that's being actively resolved for C++14 ;)

"Simpler and clearer" is a matter of opinion. For simple binding cases, bind can take a lot less typing. bind also is focused solely on function binding, so if you see std::bind, you know what you're looking at. Whereas if you use a lambda, you have to look at the lambda implementation to be certain of what it does.

Lastly, C++ does not deprecate things just because some other feature can do what it does. auto_ptr was deprecated because it is inherently dangerous to use, and there is a non-dangerous alternative.

于 2013-03-24T12:57:48.877 回答
24

您可以创建使用 lambda 无法创建的多态对象std::bind,即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;    
}

我将其创建为一个难题,而不是一个好的代码示例,但它确实演示了多态调用包装器。

于 2013-03-24T13:45:36.453 回答