将函数作为参数传递以使用 lambda 集成对象
Pass function as parameter to integrate object using lambda
用于教育目的
我有一个函数集成,它接受一个 std::function 作为参数。
double calculus::integralSimple(std::function<double(double)> fn, double begin, double end)
{
double integral = 0;
for (long double i = begin; i < end; i += _step)
{
integral += fn(i) * _step; // _step defined in class
}
return integral;
}
目前我正在使用 main 调用此函数.cpp使用
calculus cl;
std::cout << cl.integralSimple(calculus::identity,0,1);
std::cout << cl.integralSimple([](double x) { return x*x; }, 0, 1);
其中 identity 是在 calculus.h 中定义的静态函数,另一个使用 lambda 函数。
我想知道我是否可以使语法对用户来说更容易,更接近数学方式。所以我更喜欢的是用户只需要输入:
std::cout << cl.integralSimple( x*x ,0,1); // Always take a function of this form
std::cout << cl.integralSimple( x*sin(x) - x*x ,0,1);
有没有办法在C++实现这一目标?
这正是Boost.Lambda的设计目的。语法如下所示:
#include <iostream>
#include <vector>
#include <algorithm>
#include <cmath>
#include <boost/lambda/lambda.hpp>
#include <boost/lambda/bind.hpp>
const double PI =3.141592653589793238463;
double func(double v) { return std::sin(v); } // to avoid having to
// cast std::sin
int main()
{
using namespace boost::lambda;
std::vector<double> v = {0, PI / 4, PI / 2, PI};
std::for_each(v.begin(), v.end(),
std::cout << _1 * bind(func, _1) - _1 * _1 << 'n'
// ↑↑↑↑↑↑↑↑↑↑↑↑↑↑
// to delay invocation of func
);
}
这是否比 C++11 lambda 语法更好完全取决于您。
请注意,由于 C++14 和一些滥用功能,我们实际上也可以准确地编写您想要的表达式:
auto x = _1;
auto sin(decltype(_1) ) {
return bind(static_cast<double(*)(double)>(std::sin), _1);
}
有了这个,我们可以做到:
std::for_each(v.begin(), v.end(),
std::cout << x * sin(x) - x * x << 'n');
这将打印与原始示例完全相同的内容。只。。。更神秘。
相关文章:
- lambda参数转换为constexpr技巧,然后获取带链接的数组
- 将公共但非静态的成员函数与ALGLIB集成
- 可组合的lambda/std::函数与std::可选
- C++Boost Asio Pool线程,带有lambda函数和传递引用变量
- 如何建立使用模板函数的lambda函数的尾部返回类型
- 将IBM Rhapsody模型集成到VS 2019中
- 如何将lambda作为模板类的成员函数参数
- C++从其他 constexpr 创建 lambda 不能按顺序执行 Constexpr
- 在 lambda 捕获中声明的变量的类型推导
- 从R调用C++函数并对其进行集成时出错
- 我可以将调用类的"this"传递给 lambda 函数吗?
- 为什么lambda在clang上崩溃而不是在gcc上崩溃
- 模板函数指针和lambda
- 两组使用lambda函数的大括号
- 使lambda不可复制/不可移动
- FLTK:按下哪个按钮 - 将数字传递给按钮的回调 (lambda)
- 尝试将lambda函数放在队列中时出现一般分配器错误(可能是与unique_ptr有关的错误)
- 将带有unique_ptr的可变 lambda 传递给 const&std::function
- AWS Lambda C++运行时权限被拒绝
- 将函数作为参数传递以使用 lambda 集成对象