基本上,我想将此递归集成多维积分。
但是问题本身是一个普遍的问题。它不是特定于集成的。
#include "math.h"
#include <iostream>
#include <functional>
double f(double x,double y,double z){
return x+y+z+1;
}
//Base
double redDim(std::function<double(double)> &f){
return f(0); //a silly integrator for testing
}
// Recursion
template<typename Tfirst=double, typename... Trest>
auto redDim(std::function<double(Tfirst first,Trest... rest)> &f){
return redDim([=](Trest... R){return redDim([=](double x){return f(x,R...);});});
}
int main(){
std::cout<<redDim(f)<<std::endl;
return 0;
}
问题是,编译器说:
c:\C++\templateTutorial\templateTut.cpp: In function 'int main()':
c:\C++\templateTutorial\templateTut.cpp:24:19: error: no matching function for call to 'redDim(double (&)(double, double, double))'
cout<<redDim(f)<<endl;
^
c:\C++\templateTutorial\templateTut.cpp:12:8: note: candidate: 'double redDim(std::function<double(double)>&)'
double redDim(std::function<double(double)> &f){
^~~~~~
c:\C++\templateTutorial\templateTut.cpp:12:8: note: no known conversion for argument 1 from 'double(double, double, double)' to 'std::function<double(double)>&'
c:\C++\templateTutorial\templateTut.cpp:17:6: note: candidate: 'template<class Tfirst, class ... Trest> auto redDim(std::function<double(Tfirst, Trest ...)>&)'
auto redDim(std::function<double(Tfirst first,Trest... rest)> &f){
^~~~~~
c:\C++\templateTutorial\templateTut.cpp:17:6: note: template argument deduction/substitution failed:
c:\C++\templateTutorial\templateTut.cpp:24:19: note: mismatched types 'std::function<double(Tfirst, Trest ...)>' and 'double(double, double, double)'
cout<<redDim(f)<<endl;
^
The terminal process terminated with exit code: 1
那么为什么类型f
不符合要求redDim()
?
因此,即使我的方法可行,我什至无法测试。
我希望你能帮助我!
根据Yakk-Adam Nevraumont的回答,应编译以下代码:
#include "math.h"
#include <iostream>
#include <functional>
double f(double x,double y,double z){
return x+y+z+1;
}
//Base
double redDim(const std::function<double(double)> &f){
return f(0); //a silly integrator for testing
}
// Recursion
template<typename Tfirst=double, typename... Trest>
auto redDim(const std::function<double(Tfirst first,Trest... rest)> &f) {
return redDim(
std::function<double(Trest...)>{
[=](Trest... R)->double{return redDim([=](double x){return f(x,R...);});}});
}
template<class...Args>
auto redDim( double(*f)(Args...)) {
return redDim( std::function<double(Args...)>{ f } );
}
int main(){
std::cout<<redDim(f)<<std::endl;
return 0;
}
正如Yakk所指出的,std::function
函数指针的类型不同。请注意,我还将参数类型更改redDim
为const std::function<...> &)
。您也可以rvalue
使用&&
语法传递引用。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句