什么时候应该使用std :: bind? [英] When should I use std::bind?

查看:153
本文介绍了什么时候应该使用std :: bind?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

每次我需要使用 std :: bind ,我最终使用lambda。所以我应该什么时候使用 std :: bind ?我刚刚完成从一个代码库中删除它,我发现lambdas总是比 std :: bind 更简单和更清晰。是不是 std :: bind 完全不必要?不应该在将来被弃用吗?我应该在什么时候喜欢 std :: bind 到lambda函数? (必须有一个理由,它与lambdas同时达到标准。)

Every time I need to use std::bind, I end up using a lambda instead. So when should I use std::bind? I just finished removing it from one codebase, and I found that lambdas were always simpler and clearer than std::bind. Isn't std::bind completely unnecessary? Shouldn't it be deprecated in the future? When should I prefer std::bind to lambda functions? (There has to be a reason that it got into the standard at the same time as lambdas.)

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

I've also noticed that more and more people are familiar with lambdas (so they know what lambdas do). However, a lot fewer people are familiar with std::bind and std::placeholders.

推荐答案

这里是你不能用lambda做的事情:

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无法捕获只移动类型;它们只能通过复制或通过左值引用捕获值。虽然不可否认,这是一个临时问题,正在积极解决C ++ 14;)

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 ;)

更简单和更清晰是一个意见的问题。对于简单的绑定情况, bind 可以减少很多键入。 bind 也只专注于函数绑定,所以如果你看到 std :: bind 看着。如果你使用一个lambda,你必须看看lambda实现,以确定它是做什么。

"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.

最后,C ++不会弃用的东西,只是因为一些其他功能可以做它做什么。 auto_ptr 已被弃用,因为它本身就是危险的,而且有一个非危险的替代方法。

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.

这篇关于什么时候应该使用std :: bind?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆