I can't even type example code... pretty lost. Here's my original function which is NOT a lambda function (I want it to be lambda).
static void* DoublePointer(void** arg, int arg_sz) {
double* n1 = In(arg[0]);
double* n2 = In(arg[1]);
double* n3 = In(arg[arg_sz-1]);
*n3 = *n1 + *n2;
return n3;
}
void* func_ptr = DoublePointr; //works fine
But what I really want is this:
my_class.save_the_func = [](void** arg, int arg_sz) {
double* n1 = In(arg[0]);
double* n2 = In(arg[1]);
double* n3 = In(arg[arg_sz-1]);
*n3 = *n1 + *n2;
return n3;
}
my_class.point_to_func = save_the_func // point_to_func is the void* member
What do you have to do to finally get a void* pointing to the lambda function? Like I said, a non-lambda function works just fine.
The reason I want it this way is because eventually I want my code to look like this:
std::vector<function_entry> MyFuncEntry ={
add_function("MRP_DoublePointer2", "double", "double,double", "n1,n2", "add two numbers",
[](void** arg, int arg_sz)->void* {
double* n1 = In(arg[0]);
double* n2 = In(arg[1]);
double* n3 = In(arg[arg_sz-1]);
*n3 = *n1 + *n2;
return n3;
}),
add_function("MRP_DoublePointer3", "double", "double,double", "n1,n2", "add two numbers",
[](void** arg, int arg_sz)->void* {
double* n1 = In(arg[0]);
double* n2 = In(arg[1]);
double* n3 = In(arg[arg_sz-1]);
*n3 = *n1 + *n2;
return n3;
})
};
In other words, I want to define a function and some other needed parameters in the same place. Add_function returns a function_entry class that holds some strings plus the lambda function, basically I'm trying to define those strings next to the function so it's easier to maintain, it's not in two different places.
If this is bad / computationally expensive then I guess I should stick with non-lambda.
Here's the error I'm getting:
The issue with getting a void*
pointer to a lambda expression is that the result of a lambda expression is an actual honest-to-goodness object, not a pointer to an object. Just as you can't assign a std::vector
or a std::string
to a void*
, you can't assign the result of a lambda expression to a void*
.
Interestingly, the initial code you wrote - assigning a function pointer to a void*
- isn't actually guaranteed to compile! The C++ standard makes a distinction between function pointers and object pointers, and it's not portable to cast between the two of them. In fact, some compilers would outright reject your code.
If you need to store a pointer to an arbitrary function type, consider using std::function
, which is type-safe and more clearly indicates what you're trying to do.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With