Item 34: Prefer lambdas to std::bind.

Item 34: Prefer lambdas to std::bind.

Effective Modern C++ Item 34 的学习和解读。

C++11 的 std::bind 是对 C++98 std:bind1st 和 std::bind2nd 的继承,它在 2005 年以 TR1 文档形式非正式地成为标准库的一部分。因为,许多 C++ 程序员可能有十几年的 std::bind 使用经验,现在告诉他放弃使用 std::bind,多少可能有些不情愿。但是,本 Item 会告诉你使用 lambda 替代 std::bind 将是个更好的选择。

对于 C++11,除了个别边缘 case,lambda 表达式要比 std::bind 更有优势。而对于 C++14,lambda 则可以完全替代 std::bind。

lambda 第一个优势是代码的可读性更强。例如,我们有一个设置声音报警的函数:

// typedef for a point in time (see Item 9 for syntax)
using Time = std::chrono::steady_clock::time_point;
// see Item 10 for "enum class"
enum class Sound {
    Beep, Siren, Whistle };
// typedef for a length of time
using Duration = std::chrono::steady_clock::duration;
// at time t, make sound s for duration d
void setAlarm(Time t, Sound s, Duration d);

如果我们想在设置声音报警后 1h,关闭报警,并持续 30s。使用 lambda 表达式修正 setAlarm,可以实现如下:

// setSoundL ("L" for "lambda") is a function object allowing a
// sound to be specified for a 30-sec alarm to go off an hour
// after it's set
auto setSoundL =
  [](Sound s)
  {
   
    // make std::chrono components available w/o qualification
    using namespace std::chrono;
    setAlarm(steady_clock::now() + hours(1), // alarm to go off
             s, // in an hour for
             seconds(30)); // 30 seconds
  };

上述代码逻辑非常清楚。如果使用 C++14 字面值 std::literals 改写上面代码,可以更加简洁:

auto setSoundL =
  [](Sound s)
  {
   
    using namespace std::chrono
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值