如何使用类模拟 C++11 中的 lambda 函数和闭包?

How do to simulate lambda functions and closures in C++11 with classes?

本文关键字:函数 闭包 lambda 中的 何使用 模拟 C++11      更新时间:2023-10-16

假设我有一个积分函数double integral(double (*f)(double), double a, double b)它计算f(x) in [a,b]的积分。但是,我的情况是f在编译时未知,并且在运行时可能会更改。因此,在我当前的设计中,我有一个跟踪和改变几个f1, f2, f3 etc.的类。但是,由于f1, f2, f3 etc现在是类的成员,因此我不能只获取其函数指针&my_class::f1并将其提供给integral(f1,a,b)。执行此操作的理想方法是在运行时吐出一个 lambda 函数。

一些伪代码可以更准确地说明我想要的内容:

double integral(double (*f)(double), double a, double b);
class secret {
public:
// all three of these rely on internal state that this class manages
// absolutely none of these methods can be static!
double f1(double x);
double f2(double x);
double f3(double x);
void do_stuff(); // mutates internal state, changing the behavior of f1,f2,f3
void do_something_else(); // mutates internal state, changing the behavior of f1,f2,f3
double execute(); // internally, this function calls integrate(f1,a,b), integrate(f2,a,b) and integrate(f3,a,b)
}
// needs to handle functions that are not part of a class
double quadratic(double x) {
return x*x;
}
int main() {
secret s1, s2;
s1.do_stuff() // change the state of s1, changing f1,f2,f3
s2.do_something_else() // change the state of s2. 
// We can have multiple instances of the secret class, all with different internal state, 
// but need the ability to call "integral" with a lot of freedom
// I want a good design that will let me do this kind of thing
cout<<integrate(&s1.f1, 0, 1)<<endl;
cout<<integrate(&quadratic, 0, 1)<<endl;
cout<<integrate(&s2.f1, 0, 1)<<endl;
cout<<s1.execute()<<endl;
cout<<s2.execute()<<endl;
}

我仅限于一台仅支持 C++11 的旧机器。我的问题是两部分,在 C++11 中做到这一点的最佳设计是什么,以及 g++ 9.2 中最好的设计是什么?

可以通过将integral作为函数模板并将泛型类型作为函数类型来解决此问题。 用

template <typename Func>
double integral(Func func, double a, double b)
{
auto result = func(a);
// do something with result
return result;
}

允许您将函数指针和函子传递给函数。 如果您需要将成员函数传递给它,那么您只需将该调用包装到 lambda 中,然后将该 lambda 传递给类似intergral

secrete s;
auto result = integral([&s](double a){ return s.f1(a); }, 42.0, 3.14);