8

I'm having some issues working with c++ recently, its basically this:

Inside a function (lets say int main), I declared a variable Y = 5, and I have this lambda function that receives a value and adds up Y;

My problem is: I need to pass this lambda function to an already existent function, so it can be called inside the other function.

I tried a couple of things, but none of them worked as I intended (some not even worked):

double receives( double (*f)(double) )
{
    return f(5);
}

int main() 
{

    int y = 5;

    auto fun = [](double x) {
      return x + y;
    };

    cout << receives(&fun);

    return 0;
}

Another problem is that I cant change my receives function signature, the parameter must be double (*f)(double) because of the remainder of the code. I also need the lambda function to carry over the y value, without using additional parameters.

Anyone can help me on this?

João Batista
  • 123
  • 2
  • 5
  • 4
    This can't be done. The lambda would have to capture `y`, but then it would not be allowed to decay to a pointer. The only way you could do something like this would be to use a global or `static` variable for `y`, or to change the signature of `receives`. – 0x5453 Apr 20 '20 at 18:36
  • If you could change the signature to `double receives( std::function f )` it would still accept the same number and type of params that it currently does but would also accept a "stateful" lambda like you are wanting to pass in. – metal Apr 20 '20 at 18:41
  • I was afraid of that, thanks anyway, this really helped me :) If I change the signature, how can i pass the lambda to the function? Do I need to change anything else? – João Batista Apr 20 '20 at 18:41
  • Your lambda looks non-capturing but uses `y`, so I presume that's a typo and the lambda is capturing. Otherwise casting it to a function pointer wouldn't be an issue. If not, then fix the typos and edit the exact errors into the question. – rustyx Apr 20 '20 at 18:45
  • 3
    I don't see anything saying this function can't be a template. That's much less heavyweight on the codegen than using `std::function` every time you need a capturing lambda. – chris Apr 20 '20 at 18:52

1 Answers1

10

Use std::function like for example

#include <iostream>
#include <functional>

double receives( const std::function<double( double )> &f )
{
    return f( 5 );
}

int main() 
{
    int y = 5;

    auto fun = [y](double x) 
    {
      return x + y;
    };

    std::cout << receives( fun ) << '\n';

    return 0;
}
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335