为什么在C ++ 14中使用`std :: bind` over lambdas? [英] Why use `std::bind` over lambdas in C++14?

查看:159
本文介绍了为什么在C ++ 14中使用`std :: bind` over lambdas?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在C ++ 11之前,我使用了 boost :: bind boost :: lambda bind 部分使其进入标准库( std :: bind ),另一部分成为核心语言的一部分(C ++ lambdas)和使用lambdas更容易。现在,我几乎不使用 std :: bind ,因为我可以做几乎任何事情与C + + lambdas。对于 std :: bind 有一个有效的用例,我可以想到:

Before C++11 I used boost::bind or boost::lambda a lot. The bind part made it into the standard library (std::bind) the other part became part of the core language (C++ lambdas) and made the use of lambdas a lot easier. Nowadays, I hardly use std::bind, since I can do almost anything with C++ lambdas. There's one valid use-case for std::bind that I can think of:

struct foo
{
  typedef void result_type;

  template < typename A, typename B >
  void operator()(A a, B b)
  {
    cout << a << ' ' << b;
  }
};

auto f = bind(foo(), _1, _2);
f( "test", 1.2f ); // will print "test 1.2"

>

The C++14 equivalent for that would be

auto f = []( auto a, auto b ){ cout << a << ' ' << b; }
f( "test", 1.2f ); // will print "test 1.2"

(在C ++ 11中,由于auto参数,这还不行)。 std :: bind 跳过C ++ lambdas的替代方法还有其他有效的用例 std :: bind 多余的C ++ 14?

Much shorter and more concise. (In C++11 this does not work yet because of the auto parameters.) Is there any other valid use case for std::bind beating the C++ lambdas alternative or is std::bind superfluous with C++14?

推荐答案

code> std :: bind 仍然可以做一件事多态lambdas不能:调用重载的函数

std::bind can still do one thing polymorphic lambdas can't: invoke overloaded functions

struct F {
  bool operator()(char, int);
  std::string operator()(char, char);
};

auto f = std::bind(F(), 'a', std::placeholders::_1);
bool b = f(1);
std::string s = f('b');

由绑定表达式创建的调用包装器根据您给出的参数调用不同的函数,闭包从C ++ 14多态lambda可以取不同的类型参数,但不能采用不同的数字的参数,并总是调用(特殊化)相同的函数封闭。 更正:请参阅下面的注释

The call wrapper created by the bind expression calls different functions depending on the arguments you give it, the closure from a C++14 polymorphic lambda can take different types of arguments but can't take a different number of arguments, and always invokes (specializations of) the same function on the closure. Correction: see the comments below

std :: bind 返回的包装也可以用太多的参数调用,它会忽略它们,而由lambda创建的闭包将诊断尝试传递过多的参数...但我不认为 std :: bind :)

The wrapper returned by std::bind can also be called with too many arguments and it will ignore them, whereas a closure created by a lambda will diagnose attempts to pass too many arguments ... but I don't consider that a benefit of std::bind :)

这篇关于为什么在C ++ 14中使用`std :: bind` over lambdas?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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