Reputation: 16587
I have a C++ code with basic conversion functions, such as the following:
void convert(double *x_out, double *y_out, double *x_in, double *y_in)
{
*x_out = *x_in;
*y_out = *y_in;
}
I then have another function later in my code which takes a function pointer to a conversion function.
void process(void (*converter)(double *x_out, double *y_out, double *x_in, double *y_in), double x1, double y1, double x2, double y2)
{
(*converter)(x1, y1, x2, y2);
// do something
return something;
}
process
is called elsewhere in the code.
void my_func(...args...)
{
process(&convert, _x1_, _y1_, _x2_, _y2_);
}
I want to use a lambda function instead of the function pointer approach.
I can't quite get my head around lambdas.
My best guess so far from reading this http://en.cppreference.com/w/cpp/language/lambda this http://www.cprogramming.com/c++11/c++11-lambda-closures.html and this https://msdn.microsoft.com/en-gb/library/dd293608.aspx is:
void my_func(double _x1_, double _y1_, double _x2_, double _y2_)
{
[&_x1_, &_x2_, &_y1_, &_y2_] -> void
{
double x_in = _x1_;
double y_in = _y1_;
double x_out = x_in;
double y_out = y_in;
// return
_x2_ = x_out;
_y2_ = y_out;
}
process(what goes here?, _x1_, _y1_, _x2_, _y2_);
}
I'm fairly sure the declaration of the lambda goes inside the function my_func
itself, so that it can capture the local arguments/variables.
But I'm not sure how to call it from process()
?
Edits: To answer the questions below,
There is a function, process
which acts on pairs of data, x and y, but before process operates on this data, it must be converted using a translation function. The example I have given as a translation is trivially, x->x y->y, but a more interesting one might be x->2x, y->0.5y.
Error Message:
no known conversion for argument 1 from
‘namespace::classname::my_func(uint32_t, uint32_t, uint32_t,
uint32_t)::<lambda(int32_t*, const int32_t*, int32_t*, const
int32_t*)>’ to ‘void (namespace::classname::*)(int32_t*, const
int32_t*, int32_t*, const int32_t*) {aka void
(namespace::classname::*)(int*, const int*, int*, const int*)}’
Arguments in examples should have been int32_t
rather than double, but this is clearly not of the upmost importance.
Upvotes: 0
Views: 1074
Reputation: 62563
Non-capturing lambdas can be converted to function pointers seamlessly. And you do not seem to need captures here. Following code would work:
void my_func(double _x1_, double _y1_, double _x2_, double _y2_)
{
auto lam = [](double* x_in, double* y_in, double* x_out, double* y_out)
{
*x_out = *x_in;
*y_out = *y_in;
};
process(lam, _x1_, _y1_, _x2_, _y2_);
}
Upvotes: 2