我有一段带有基本转换函数的C++代码,如下所示:
void convert(double *x_out, double *y_out, double *x_in, double *y_in)
{
*x_out = *x_in;
*y_out = *y_in;
}
然后我的代码中有另一个函数,它接受一个指向转换函数的函数指针。
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
在代码的其他地方被调用。
void my_func(...args...)
{
process(&convert, _x1_, _y1_, _x2_, _y2_);
}
我想使用 lambda 函数而不是函数指针方法。
我不太了解 lambda。
到目前为止,我最好的猜测是阅读这篇 http://en.cppreference.com/w/cpp/language/lambda这个http://www.cprogramming.com/c++11/c++11-lambda-closures.html还有这个https://msdn.microsoft.com/en-gb/library/dd293608.aspx是:
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_);
}
我相当确定 lambda 的声明进入函数 my_func
本身,以便它可以捕获局部参数/变量。
但我不确定如何从 process()
中调用它?
编辑:回答下面的问题,
有一个函数 process
作用于数据对 x 和 y,但在 process 对该数据进行操作之前,必须使用转换函数对其进行转换。我给出的翻译示例很简单,x->x y->y,但更有趣的可能是 x->2x,y->0.5y。
错误信息:
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*)}’
示例中的参数应该是 int32_t
而不是 double,但这显然不是最重要的。
最佳答案
非捕获 lambda 可以无缝地转换为函数指针。而且您似乎不需要在这里捕获。以下代码将起作用:
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_);
}
关于c++ - 如何将我的转换函数转换为 lambda 表达式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36897968/