c++ - 如何在 C++ 中使用单个模板参数传递两个 lambda 函数

标签 c++ templates lambda types functional-programming

我正在编写一个程序来计算 voigt 分布的数值。但是,当我尝试使用单个类模板参数 F 传递 gauss 和 lorentz 函数时遇到问题,即使它们属于同一类型。

当我使用两个模板参数时,比如说 F1F2,它就像一个魅力。但是只要只有一个,g++ 就会抛出一个错误。立即将 lambda 作为 splot 的(卷积)参数传递没有帮助。

#define _USE_MATH_DEFINES

#include <iostream>
#include <cmath>
#include <functional>

using namespace std;

#define MIN -10.
#define MAX 10.
#define EPS 0.01

template <typename T, class F> T trapezoid(F f, T a, T b, T eps) {
    T result = T(0);
    while (a <= b) {
        result += f(a);
        a += eps;
    }
    result -= (f(a) + f(b)) / T(2);
    return result * eps;
}

template <class F>
double splot(F g, F l, double x, double sigma, double gamma) {

    auto s = [g, l, x, sigma, gamma](double x_prime)->double {
        return g(x_prime, sigma) * l(x - x_prime, gamma);
    };

    return trapezoid(s, MIN, MAX, EPS);
}

int main (void) {
    double x = 0., sigma = 1.5, gamma = 0.1;

    auto gauss = [](double x, double sigma)->double {
        return exp(-1*x*x / (2*sigma*sigma)) / (sigma * sqrt(2*M_PI));
    };

    auto lorentz = [](double x, double gamma)->double {
        return gamma / (M_PI*(x*x + gamma*gamma));
    };

    cout << "x: " << x << endl << "V(x): " <<
     splot(gauss, lorentz, x, sigma, gamma) << endl;

    return 0;
}

最佳答案

我建议您使用 std::function<>如下图:

typedef std::function<double(double,double)> func;

func gauss = [](double x, double sigma)->double {
    return exp(-1*x*x / (2*sigma*sigma)) / (sigma * sqrt(2*M_PI));
};

func lorentz = [](double x, double gamma)->double {
    return gamma / (M_PI*(x*x + gamma*gamma));
};

cout << "x: " << x << endl << "V(x): " <<
 splot(gauss, lorentz, x, sigma, gamma) << endl;`

正如@Christophe 指出的那样,lambda 将具有不同的类型,而另一方面,确保您为所有方法保持相同的类型。

关于c++ - 如何在 C++ 中使用单个模板参数传递两个 lambda 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55559897/

相关文章:

templates - 将列表分配给图表中的键

c++ - 生成保证顺序执行吗?

javascript - 如何解决单元测试中的异步等待 - javascript

c++ - 仅包含 RGB 565 红色分量的图像

c++ - 在 C++ 中按列保存矩阵

c++ - 删除指针: delete/delete[]/free?的方法

javascript - Meteor:如何获取对象属性的响应式(Reactive)父/子依赖模板

c++ - Linux Mint 19 上的 CMake 3.11 无法找到静态 Boost 库

templates - 如何使用 Go 将多个字符串解析为一个模板?

java - 为什么这个 lambda 可以在这里使用,其中需要 Arrays.sort() 中的比较器