c++ - 不能使用以 lambda 作为参数的模板函数

标签 c++ c++11 lambda

我有模板函数,函数指针作为模板参数。当我使用全局函数指针作为模板参数时,一切正常。当我尝试使用 lambda(不捕获)在本地定义函数时,会出现问题。 这是最少的代码:

#include <vector>
#include <iostream>

template<double (*f)(double, double)>
std::vector<double> calculate(std::vector<double>& x, std::vector<double>& y){
    std::vector<double> z(x.size());
    std::transform(x.begin(),x.end(),y.begin(),z.begin(),f);
    return z;
}

double calc(double n, double k){
    return n*n+k*k;
}

int main(int argc, char *argv[])
{
    double (*fun)(double,double) = [](double n, double k){return n*n+k*k;};
    std::vector<double> x(5,3);
    std::vector<double> y(5,4);
    std::vector<double> z1 = calculate<&calc>(x,y);//it works fine
    std::vector<double> z2 = calculate<fun>(x,y);//this line gives a bunch of errors

    for(int i=0;i<z1.size();i++){
        std::cout<<z1[i]<<" ";
    }
    for(int i=0;i<z2.size();i++){
        std::cout<<z2[i]<<" ";
    }
    return 0;
}

这里是错误:

  1. the value of 'fun' is not usable in a constant expression
  2. no matching function for call to 'calculate(std::vector<double>&, std::vector<double>&)
  3. 'fun' is not a valid template argument for type 'double (*)(double, double)'
  4. it must be the address of a function with external linkage

最佳答案

calc 是常量,可以用作模板参数,而 fun 是变量,因此不能。

不幸的是,你不能直接将 lambda 作为模板参数传递,因为你不能(标准说你不能)...所以下面的方法不会起作用:

calculate<[](double n, double k){ return n*n+k*k; }>(x, y);

在您的具体情况下,不清楚为什么该函数是模板参数而不仅仅是参数...(在这种情况下传递 fun 会很好)。

关于c++ - 不能使用以 lambda 作为参数的模板函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33815285/

相关文章:

c++ - 如何正确地将 char ** x 转换为 const char **

c++ - 无法解析 SystemC sc_signal_resolved

c++ - 如何读取 csv 文件?

c++ - 可能的模板解决方案

c++ - 如何将 int 复制到 boost/std::char 数组?

c++ - std::c++ 静态分配函数

c++ - 是否有用于 boost.build 的 IDE(最好是 netbeans)插件?

c++ - 函数对象转换为函数指针

kotlin - 如何在Kotlin中替换长链的forEach {}语句?

c++ - 使用 Auto 和 Lambda 处理信号?