我有模板函数,函数指针作为模板参数。当我使用全局函数指针作为模板参数时,一切正常。当我尝试使用 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;
}
这里是错误:
-
the value of 'fun' is not usable in a constant expression
-
no matching function for call to 'calculate(std::vector<double>&, std::vector<double>&)
-
'fun' is not a valid template argument for type 'double (*)(double, double)'
-
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/