user56643 user56643 - 18 days ago 7
C++ Question

Header for nested C++ lambda function

Consider the following (simplified) example where two lambda functions call each other, one of which also takes another function as an argument. I need to use lambda functions, since the functions also pass modified, nested functions between each other.

#include <iostream>
using namespace std;

auto f = [](int n, auto h)
{
if(n >= 5) return n;
cout << "h is some function " << h(4.0) << end;
auto func = [](int m){ return m*h(m); }; // some nested function
return g(n+1,func);
};

auto g = [](int n, auto h)
{
if(n >= 5) return n;
cout << "h is some function " << h(5.0) << end;
auto func = [](int m){ return m*h(m); }; // some nested function
return f(n+1,func);
};

int main()
{
auto initial_function = [](int m){ return m*m; };
f(1, initial_function);
return 0.0;
}


This returns the usual error undeclared identifier 'g' which was to expect since there is no header file. So my question is: What is the proper syntax to declare the two lambda functions?

Answer

This works on my machine:

#include <functional>
#include <iostream>
#include <stdio.h>
using namespace std;

extern function<int(int, function<int(int)>)> g;

auto f = [](int n, function<int(int)> h)
{
    if (n >= 5) return n;
    cout << "h is some function " << h(4.0) << endl;
    auto func = [h](int m) { return m*h(m); };   
    return g(n + 1, func);
};

function<int(int, function<int(int)>)> g = [](int n, function<int(int)> h)
{
    if (n >= 5) return n;
    cout << "h is some function " << h(5.0) << endl;
    auto func = [h](int m) { return m*h(m); };   
    return f(n + 1, func);
};

int main()
{
    auto initial_function = [](int m) { return m*m; };
    f(1, initial_function);

    getchar();
    return 0; // Return value of the function is int so its better to use 0 rather than 0.0
}