When should I use std::bind?

拟墨画扇 提交于 2019-11-29 22:54:20

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.

You can create polymorphic objects with std::bind which you can't with lambdas, i.e. the call wrapper returned by std::bind can be invoked with different argument types:

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

I created this as a puzzle not an example of good code, but it does demonstrate polymorphic call wrappers.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!