0

C++14 lambda 用法

 2 years ago
source link: https://forrestsu.github.io/posts/cpp/cpp14-lambda-usage/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

C++14 lambda 用法

2020年2月7日
| 字数 920
| CPP
| 阅读 36

1 嵌套lambda表达式

写一个lambda表达式A,其入参是一个lambda表达式B:

#include <cstdio>
#include <iostream>

namespace example01 {

template<typename Func>
void run_task(Func &&func) {
    int arg = 100;
    printf("1. arg >> %d\n", arg);
    /**
     * 定义一个别名,进行引用捕获
     * (注意:引用捕获时,请考虑被捕获对象的生命周期)
     */
    func([&i = arg]() mutable {
        ++i;
        printf("3. i == %d\n", i);
        throw std::logic_error("逻辑错误");
    });
    printf("6. arg << %d\n", arg);
}

inline void run() {
    //写一个lambda表达式A,其入参是一个lambda表达式B
    example01::run_task([](auto get_ex) {
        printf("2. start check\n");
        try {
            get_ex();
        } catch (std::exception &ex) {
            std::cout << "4. accept failed: " << ex.what() << "\n";
        }
        printf("5. end check\n");
    });
}
} //namespace example

int main() {
    example01::run();
    return 0;
}

输出结果如下:

  1. arg » 100
  2. start check
  3. i == 101
  4. accept failed: 逻辑错误
  5. end check
  6. arg « 101

当嵌套使用lambda表达式时,代码比较难读,代码书写的顺序和执行顺序差异很大!


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK