【发布时间】:2021-12-07 21:20:07
【问题描述】:
我有一个带有签名的函数:
template<class Type>
bool isPrime(const Type& n,float (*fSqrt)(float),bool debug = false)
效果很好。但是,
template<class Type>
bool isPrime(const Type& n,std::function<float(float)> fSqrt,bool debug = false)
导致编译错误。
如何将float (*fSqrt)(float) 替换为std::function<float(float)> fSqrt ?
请注意:我的最终目标是 std::function<float(Type)>,其中 Type 是模板化的。
魔杖盒 (https://wandbox.org/) 显示:
prog.cc: In function 'int main()':
prog.cc:91:28: error: no matching function for call to 'isPrime(int&, <unresolved overloaded function type>, bool)'
91 | std::cout<<(isPrime(n,std::sqrt,true)?"Positive":"Negative")<<'\n';
| ~~~~~~~^~~~~~~~~~~~~~~~~~
prog.cc:10:27: note: candidate: 'template<class Type> bool isPrime(const Type&, const float&, bool)'
10 | template<class Type> bool isPrime(const Type& n,const float& nSqrt = 0.0,bool debug = false) {
| ^~~~~~~
prog.cc:10:27: note: template argument deduction/substitution failed:
prog.cc:91:28: note: cannot convert 'std::sqrt' (type '<unresolved overloaded function type>') to type 'const float&'
91 | std::cout<<(isPrime(n,std::sqrt,true)?"Positive":"Negative")<<'\n';
| ~~~~~~~^~~~~~~~~~~~~~~~~~
prog.cc:81:27: note: candidate: 'template<class Type> bool isPrime(const Type&, std::function<float(float)>, bool)'
81 | template<class Type> bool isPrime(const Type& n,std::function<float(float)> fSqrt,bool debug = false) { // Type & std::function - compile-error
| ^~~~~~~
prog.cc:81:27: note: template argument deduction/substitution failed:
prog.cc:91:28: note: cannot convert 'std::sqrt' (type '<unresolved overloaded function type>') to type 'std::function<float(float)>'
91 | std::cout<<(isPrime(n,std::sqrt,true)?"Positive":"Negative")<<'\n';
| ~~~~~~~^~~~~~~~~~~~~~~~~~
OnlineGDB (https://www.onlinegdb.com/#) 显示:
main.cpp:91:38: error: no matching function for call to ‘isPrime(int&, , bool)’
std::cout<<(isPrime(n,std::sqrt,true)?"Positive":"Negative")<<'\n';
^
main.cpp:10:27: note: candidate: template bool isPrime(const Type&, const float&, bool)
template<class Type> bool isPrime(const Type& n,const float& nSqrt = 0.0,bool debug = false) {
^~~~~~~
main.cpp:10:27: note: template argument deduction/substitution failed:
main.cpp:91:38: note: cannot convert ‘sqrt’ (type ‘’) to type ‘const float&’
std::cout<<(isPrime(n,std::sqrt,true)?"Positive":"Negative")<<'\n';
^
main.cpp:81:27: note: candidate: template bool isPrime(const Type&, std::function, bool)
template<class Type> bool isPrime(const Type& n,std::function<float(float)> fSqrt,bool debug = false) { // Type & std::function - compile-error
^~~~~~~
main.cpp:81:27: note: template argument deduction/substitution failed:
main.cpp:91:38: note: cannot convert ‘sqrt’ (type ‘’) to type ‘std::function’
std::cout<<(isPrime(n,std::sqrt,true)?"Positive":"Negative")<<'\n';
^
【问题讨论】:
-
sqrt已超载,您必须将其转换为static_cast<float(*)(float)>(std::sqrt)才能选择正确的。 -
只需将
std::sqrt更改为::sqrt。
标签: c++ function c++11 templates std-function