0

I have a class which uses lambda in one of its constructor, and I am having trouble understanding how it gets executed

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});
};

The constructors

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) 
{};

Constructor in question

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

If I create an object of type check using the following

check db_intl{"Test", db_dur};

The following constructor gets called

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

How is this constructor able to call the other constructor with the lambda if that lambda is not being used?

1 Answer 1

1

Since pred is typedefed to std::function<bool(int)>, the lambda will be converted to a pred, and construction is then delegated to the 3rd constructor (check(std::string, pred, msec duration = msec{0}). The lambda will then be stored in the _predicates container and (presumably) called later when the predicates are invoked.

Sign up to request clarification or add additional context in comments.

2 Comments

_predicates is defined as pred_list const _predicates; If i create an object of type check like this check db_intl{"Test", db_dur}; It is only passing 2 parameters, and in the third constructor there is no local variable which can be used for the lambda
@zer0c00l The two parameter constructor will delegate to the three parameter one; see the "Delegating constructor" section on cppreference. The lambda is not using any local variables.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.