[英]Convert Object Based Lambda to Function Pointer
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? 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!谢谢你的帮助!
Ok, so I solved this with a functional object:好的,所以我用功能 object 解决了这个问题:
So not only the function, also the necesarry variables are stored:因此,不仅 function,还存储了必要的变量:
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.它工作正常。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.