如何使用类模拟 C++11 中的 lambda 函数和闭包?
How do to simulate lambda functions and closures in C++11 with classes?
假设我有一个积分函数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);
相关文章:
- 如何将C++闭包与变量参数同时重用——类似于JavaScript
- C++中的 JavaScript 样式闭包
- 如何使用类模拟 C++11 中的 lambda 函数和闭包?
- 组合函数参数包和默认参数
- 关于函数模板中定义的 lambda 闭包类型可以说些什么?
- 通过引用将自定义结构的向量传递给 boost::compute 闭包或函数
- 在 c++ 中使用函数装饰器(使用闭包)时出现意外的分段错误
- Lambda 表达式闭包函数不起作用
- Lambda 闭包类型构造函数
- 在闭包中,如何通过存储在内存中的指针或引用类型捕获可变性或用现代函数式语言进行处理?
- 没有声明和初始化的类似闭包的函数(即没有'auto f = make_closure();')
- c++11 lambda 真的支持闭包吗?函数变量中存在语义冲突
- 如何将局部引用的变量传递给 lambda 函数,但该函数将在闭包完成后调用
- C++定义一个使用lambda闭包的函数
- 从函数返回的 C++ lambda 闭包类型
- 如何在给定函数之外获取与 C 闭包关联的(向上)值
- 了解Lambda闭包类型如何删除默认构造函数
- 从lambda的内部框架修改via闭包中的变量安全吗?lambda是从一个不再存在的函数创建的
- 如何从函数返回闭包?
- 是否可以在C++11之前创建函数局部闭包