Search code examples
c++pointersclosuresfunction-pointersreturn-type

Return type of closure in C++


I am trying to learn closures in C++. This example works:

auto add_n(int n) {
    return [=](int x) -> int {
        return x + n;
    };
};
auto add_3 = add_n(3);
add_3(5); //8

What type is add_n expecting out? I would expect to be able to use a function pointer that takes in an int and returns an int as the return type?

typedef int (*fptr)(int);
fptr add_n(int n) {
    return [=](int x) -> int {
        return x + n;
    }; 
};

Additionally, would anything else need to be done if I am working with templates instead? Thank you!


Solution

  • Each lambda has its own unnamed types, so you cannot replace auto by its real type.

    Lambda with capture cannot be converted to function pointer.