构造函数中的 Lambda

Lambda in constructor

本文关键字:Lambda 构造函数      更新时间:2023-10-16

>我有一个在其构造函数中使用lambda的类,我很难理解它是如何执行的

using pred = std::function<bool(int)>;
using pred_list = std::vector<pred>;
class check
{
    private:
        std::string const _description;
    public:
        check(std::string, msec duration = msec{0});
        check(std::string, pred_list, msec duration = msec{0});
        check(std::string, pred, msec duration = msec{0});
};

构造函数

check::check(std::string d, pred_list p, msec dur)
: _description{d}, _duration{dur}, _predicates{p}, _pred_pass{false}
, _deadline{msec::max()}
{};
check::check(std::string d, pred p, msec dur)
: _description{d}, _duration{dur}, _predicates{1,p}, _pred_pass(false)
{};
check::check(std::string s, msec dur)
: check(s, [](int i) { return i > 0; }, dur) 
{};

有问题的构造函数

check::check(std::string s, msec dur)
: check(s, [](int i) { return i > 0; }, dur) 
{};

如果我使用以下方法创建类型检查的对象

check db_intl{"Test", db_dur};

调用以下构造函数

check::check(std::string s, msec dur)
: check(s, [](int i) { return i > 0; }, dur) 
{};

如果未使用另一个构造函数,此构造函数如何能够使用 lambda 调用该构造函数?

由于 pred 的类型定义为 std::function<bool(int)>,lambda 将被转换为 pred,然后构造委托给第 3 个构造函数 (check(std::string, pred, msec duration = msec{0}) 。 然后,lambda 将存储在 _predicates 容器中,并在稍后调用谓词时(大概(调用。