1

say I have this program situation overhere:

struct A
{
    int(*func_ptr)();
};

struct B
{
    int b = 0;
    void SetFunctionPointerToLambda(A& a)
    {
        a.func_ptr = [=] () { return b; };
    }
};

int main()
{
    A a;
    B b;
    b.SetFunctionPointerToLambda(a);
}

I want to set a function pointer of an object A to a lambda, which is based of the values of an object B. So, how is this going to be done?

Current error message:

loeschen5.cc: In member function 'void B::SetFunctionPointerToLambda(A&)':
loeschen5.cc:14:41: error: cannot convert 'B::SetFunctionPointerToLambda(A&)::<lambda()>' to 'int (*)()' in assignment
         a.func_ptr = [=] () { return b; };
                                         ^

Thanks for any help!

Konrad Rudolph
  • 530,221
  • 131
  • 937
  • 1,214
DesktopDev
  • 21
  • 3
  • 1
    Does this answer your question? [Passing capturing lambda as function pointer](https://stackoverflow.com/questions/28746744/passing-capturing-lambda-as-function-pointer) – Osyotr Dec 12 '21 at 16:16
  • 1
    To be able to capture `b` the lambda has to behave like a struct. So cannot be converted to a function pointer. – BoP Dec 12 '21 at 16:17
  • Okay, so when im sure in some case, that b will not change, can I somehow replace b with the actual value of b ( = 0)? – DesktopDev Dec 12 '21 at 16:21
  • ... or can I somehow pass the address of b into the lambda? – DesktopDev Dec 12 '21 at 16:22
  • Sure, you can, you'll just have to change the function pointer to a pointer to a function that takes a parameter. – Sam Varshavchik Dec 12 '21 at 16:33

1 Answers1

0

Ok, so I solved this with a functional object:

So, not only the function, but also the necessary variables are stored:

struct FunctionObject
{
    const int *b;
    int operator ()() const
    {
        return *b;
    }
};

struct A
{
    FunctionObject func_ptr;
};

struct B
{
    int b = 56;
    void SetFunctionPointerToLambda(A& a) const
    {
        a.func_ptr = FunctionObject { &b };
    }
};

int main()
{
    A a;
    B b;
    b.SetFunctionPointerToLambda(a);
}

And it works fine.

Adrian Mole
  • 49,934
  • 160
  • 51
  • 83
DesktopDev
  • 21
  • 3