Lambda fun
C++ lambdas give you the ability to create a local member function that can access the values in the enclosing unit.
A simple example
#include <iostream>
using namespace std;
int main()
{
int x = 5;
auto isEmpty = [x](auto val)->auto { std::cout << x << ", " << val << std::endl; return val; };
cout << isEmpty(true) << endl;
}
A lambda can be declared globally
#include <iostream>
using namespace std;
class Point
{
public:
Point(int px, int py) :x(px), y(py) {}
const int& getX() const { return x; }
const int& getY() const { return y; }
private:
int x;
int y;
};
auto isEqual = [](auto &pp)->bool {return pp.getX() == pp.getY(); };
int main()
{
int x = 5;
auto isEmpty = [x](auto val)->auto { std::cout << x << ", " << val << std::endl; return val; };
cout << isEmpty(true) << endl;
}
A lambda cannot be declared as a member variable
#include <iostream>
using namespace std;
class Point
{
public:
Point(int px, int py) :x(px), y(py) {}
const int& getX() const { return x; }
const int& getY() const { return y; }
private:
int x;
int y;
auto isEqual = [](auto &pp)->bool {return pp.getX() == pp.getY(); }; // This line will NOT compile
};
int main()
{
int x = 5;
auto isEmpty = [x](auto val)->auto { std::cout << x << ", " << val << std::endl; return val; };
cout << isEmpty(true) << endl;
Point np{ 4, 7 };
}