简体   繁体   English

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

[英]When should I use std::bind?

Every time I need to use std::bind , I end up using a lambda instead. 每当我需要使用std::bind ,我最终都会使用lambda代替。 So when should I use std::bind ? 所以我什么时候应该使用std::bind I just finished removing it from one codebase, and I found that lambdas were always simpler and clearer than std::bind . 我刚从一个代码库中删除它,我发现lambda总是比std::bind更简单明了。 Isn't std::bind completely unnecessary? std::bind完全没有必要吗? Shouldn't it be deprecated in the future? 将来不应该弃用吗? When should I prefer std::bind to lambda functions? 我什么时候应该首选std::bind到lambda函数? (There has to be a reason that it got into the standard at the same time as lambdas.) (一定有理由要使它与lambdas同时进入标准。)

I've also noticed that more and more people are familiar with lambdas (so they know what lambdas do). 我还注意到,越来越多的人熟悉lambda(因此他们知道lambda的作用)。 However, a lot fewer people are familiar with std::bind and std::placeholders . 但是,很少有人熟悉std::bindstd::placeholders

Here's something you can't do with a lambda: 这是lambda无法做到的:

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

Lambdas can't capture move-only types; Lambda无法捕获仅移动类型。 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 ;) 尽管诚然这是一个暂时的问题,但对于C ++ 14来说正在积极解决中;)

"Simpler and clearer" is a matter of opinion. “更简单,更清晰”是一个见解。 For simple binding cases, bind can take a lot less typing. 对于简单的绑定情况, bind可以减少很多键入工作。 bind also is focused solely on function binding, so if you see std::bind , you know what you're looking at. bind也只专注于函数绑定,因此,如果您看到std::bind ,便知道您在看什么。 Whereas if you use a lambda, you have to look at the lambda implementation to be certain of what it does. 而如果您使用lambda,则必须查看lambda实现以确认其功能。

Lastly, C++ does not deprecate things just because some other feature can do what it does. 最后,C ++并不仅仅因为某些其他功能可以完成其工作而弃用某些东西。 auto_ptr was deprecated because it is inherently dangerous to use, and there is a non-dangerous alternative. 不建议使用auto_ptr ,因为使用它具有内在的危险 ,并且存在非危险的替代方法。

You can create polymorphic objects with std::bind which you can't with lambdas, ie the call wrapper returned by std::bind can be invoked with different argument types: 您可以使用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;    
}

I created this as a puzzle not an example of good code, but it does demonstrate polymorphic call wrappers. 我将其创建不是一个好的示例示例,而是一个难题 ,但是它确实演示了多态调用包装器。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM