federico-busato / Modern-CPP-Programming

Modern C++ Programming Course (C++03/11/14/17/20/23/26)
https://federico-busato.github.io/Modern-CPP-Programming/
11.91k stars 798 forks source link

Question : I'm a little confused about the content of the 28th slide of Basic Concepts V #96

Closed ChoiSeonMun closed 5 months ago

ChoiSeonMun commented 5 months ago

Hi there.

I came here because I was studying and had trouble understanding something intuitively. The 28th slide says that A function can return a lambda (dynamic dispatch is also possible) image

I'm wondering if the code below describes your intent.

auto f(int type) -> bool(*)(int, int)
{
    if (type % 2 == 0)
    {
        return [](int lhs, int rhs) { return lhs < rhs; };
    }
    else
    {
        return [](int lhs, int rhs) { return lhs > rhs; };
    }
}

If my understanding is not correct, could you unpack it a bit more and explain?

federico-busato commented 5 months ago

Hi @ChoiSeonMun, your understanding is correct. Note that you can only return a lambda as a function pointer bool(*)(int, int) only if it doesn't capture anything. Otherwise, dynamic dispatching will not work. I may need to clarify this point in the slides.