问题描述
如措辞类似的问题中所述()答案是-没有理由(并且还提到了为什么最好使用lambdas)。
As mentioned in a similarly worded question (Why use bind over lambdas in c++14?) The answer was - no reason (and also mentioned why it would be better to use lambdas).
我的问题是-如果在C ++ 14中不再有使用绑定的理由,为什么标准委员会认为有必要添加在C ++ 20中?
My question is - if in C++14 there was no longer a reason to use bind, why did the standards committee found it necessary to add std::bind_front
in C++20?
与lambda相比,它现在具有任何新的优势吗?
Does it now have any new advantage over a lambda?
推荐答案
bind_front
绑定前X个参数,但如果可调用要获取更多参数,它们将附加在最后。当您仅绑定函数的前几个参数时,这使得 bind_front
非常可读。
bind_front
binds the first X parameters, but if the callable calls for more parameters, they get tacked onto the end. This makes bind_front
very readable when you're only binding the first few parameters of a function.
显而易见的示例是创建一个可用于绑定到特定实例的成员函数:
The obvious example would be creating a callable for a member function that is bound to a specific instance:
type *instance = ...;
//lambda
auto func = [instance](auto &&... args) -> decltype(auto) {return instance->function(std::forward<decltype(args)>(args)...);}
//bind
auto func = std::bind_front(&type::function, instance);
bind_front
版本是 lot 少吵。它指向正确的位置,恰好具有3个命名的事物: bind_front
,要调用的成员函数以及将在其上调用的实例。这就是我们情况所需要的:一个标记,表示我们正在创建一个函数的第一个参数,要绑定的函数以及要绑定的参数的绑定。没有多余的语法或其他细节。
The bind_front
version is a lot less noisy. It gets right to the point, having exactly 3 named things: bind_front
, the member function to be called, and the instance on which it will be called. And that's all that our situation calls for: a marker to denote that we're creating a binding of the first parameters of a function, the function to be bound, and the parameter we want to bind. There is no extraneous syntax or other details.
相比之下,lambda有很多我们不在乎的东西。 auto ... args
位, std :: forward
之类的东西,以此类推。这很难弄清楚
By contrast, the lambda has a lot of stuff we just don't care about at this location. The auto... args
bit, the std::forward
stuff, etc. It's a bit harder to figure out what it's doing, and it's definitely much longer to read.
请注意, bind_front
不允许 bind
的占位符,因此它并不是真正的替代。对于 bind
的最有用形式而言,它更是简写形式。
Note that bind_front
doesn't allow bind
's placeholders at all, so it's not really a replacement. It's more a shorthand for the most useful forms of bind
.
这篇关于为什么在C ++ 20中对lambda使用`std :: bind_front`?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!