Lambdas in C++. How it works

Consider this code example:

void f(int i)
{
    auto g = [i](auto j)
    {
        return i + j;
    };
    g = [i](auto j)
    {
        return i - j;
    };
    g(1);
}

When compiling

arise

line error

g = [i](auto j)

.

Why is this happening?


The fact is that lambdas in C ++ are just syntactic sugar over local classes / structures with a certain [возможно шаблонным] bracket operator:

class Lambda1
{
    int i;

public:
    Lambda1(int i) : i(i) {}

    template <class Ty> auto operator()(Ty j)
    {
        return i + j;
    }
};

class Lambda2
{
    int i;

public:
    Lambda2(int i) : i(i) {}

    template <class Ty> auto operator()(Ty j)
    {
        return i - j;
    }
};

void f(int i)
{
    auto g = Lambda1(i);
    g = Lambda2(i);
    g(1);
}

Now cause the error

[в строке g = Lambda2(i);]

becomes obvious: Lambda1 and Lambda2 are different classes that do not know anything about each other.

These classes had to be made global, because C++ still doesn’t support template methods in local classes.

In conclusion.

In order for the given code examples to compile, it is enough to replace

auto g

on the

std::function<int(int)> g

.

(How does it work

std::function

This is a topic for a separate article.)

Similar Posts

Leave a Reply