0

I have a hard time understanding how lambda capture works, specifically how it catches arguments within the lambda. I spent several hours reading the same trivial examples about lambdas and still no clarity.

Here is context. I have a class Node:

class EventComparisonNode : public Node{ //or Date comparison node, only difference is instead of event there is Date struct
 public:
  EventComparisonNode(Comparison cmp, const std::string& event);
  bool Evaluate(const Date& date, const std::string& event) override; //Date struct contains ints
 private:
  Comparison cmp_; //it's enum
  std::string event_;
};

And I have this piece of code

//ParseCondition returns shared_ptr<Node>
auto condition = ParseCondition(is);
auto predicate = [condition](const Date& date, const string& event) {
    return condition->Evaluate(date, event);
};

My questions here are:

What predicate exactly is? Is it some custom lambda type or what?

At the second string, I capture shared_ptr. Ok. But where Date and string& types coming from? I can't see there any structure or variable or anything, where it can be taken from (both at the same time). Variables are not coming out of anywhere.

Btw, full code available here:(not my rep)

https://github.com/freeraisor/yandexcplusplus/blob/master/2.%20Yellow/Final%20Project/main.cpp

Thank you for your attention!

Chinez
  • 551
  • 2
  • 6
  • 29
  • The main question here *might be* ["What is a callable?"](https://stackoverflow.com/questions/19278424/). Alternately "what is a lambda?", "what is a lambda capture?" – Drew Dormann Feb 03 '21 at 20:10
  • A lambda is a shorthand way for making a small class w/ member variables (what gets captured), and a function named `operator()` (so that instances of the class can get called as if they were a function). The arguments to `operator()` are the same as the arguments to your lambda (`const Date& date, const string& event`) – AndyG Feb 03 '21 at 20:11
  • IOW, `auto predicate = [condition](const Date& date, const string& event) { return condition->Evaluate(date, event); };` is roughly equivalent to `struct lambda_XYZ { shared_ptr condition; bool operator()(const Date& date, const string& event) const { return condition->Evaluate(date, event); }; lambda_XYZ predicate{condition};` – Remy Lebeau Feb 03 '21 at 20:24

0 Answers0