我應該如何修改我目前的函式簽名
template<class TypeData,typename TypeFunc1 = Identity,typename TypeFunc2>
bool isPrime(const TypeData& n,TypeFunc1 calcSqrt = {},TypeFunc2 isDivisible = [](const TypeData& a,const TypeData& b) {return a%b==0;},const bool debug = false)
為了被呼叫
auto fSqrt = [](decltype(n) v) {return std::sqrt(static_cast<float>(v));};
std::cout<<(isPrime(n,fSqrt)?"Positive":"Negative")<<'\n';
Visual Studio 2019 提供
C2783 'bool isPrime(const TypeData &,TypeFunc1,TypeFunc2,const bool)': 無法推匯出 'TypeFunc2' 的模板引數
TypeFunc2 isDivisible = [](const TypeData& a,const TypeData& b) {return a%b==0;}不過,沒有 一切都很好。
傳遞默認 lambda 的正確語法是什么?
請幫助我,請。
uj5u.com熱心網友回復:
問題是默認引數對模板引數中的型別推導沒有貢獻。
這可以通過以下主要示例顯示:
template <typename X>
void f(X a = 2);
int main() {
f(); // The compiler spits out an error since it cannot determine the type 'X' holds
}
在這種情況下,您需要做的是改用函式多載:
// ...
template<class TypeData, typename TypeFunc1, typename TypeFunc2>
bool isPrime(const TypeData& n,
TypeFunc1 calcSqrt,
TypeFunc2 isDivisible,
const bool debug);
template<class TypeData>
bool isPrime(const TypeData& n) {
return isPrime(n, Identity{}, [](const TypeData& a, const TypeData& b) {
return a % b == 0;
}, false);
}
// ...
uj5u.com熱心網友回復:
Ruks的回答其實很好。另一種選擇是使用 std::function,它也可能適合您的需求:
template<class TypeData,typename TypeFunc1=Identity,typename TypeFunc2 = std::function<bool(const TypeData&, const TypeData&)>>
bool isPrime(
const TypeData& n,
TypeFunc1 calcSqrt = {},
TypeFunc2 isDivisible = [](const TypeData& a,const TypeData& b) {return a%b==0;},
const bool debug = false);
uj5u.com熱心網友回復:
您需要為您添加一個默認型別TypeFunc2,例如:
template<class TypeData,
typename TypeFunc1 = Identity,
typename TypeFunc2 = bool(*)(const TypeData&,const TypeData&)>
//^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
bool isPrime(const TypeData& n,
TypeFunc1 calcSqrt = {},
TypeFunc2 isDivisible = [](const TypeData& a,const TypeData& b) {return a%b==0;},
const bool debug = false) {
// ...
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/339987.html
上一篇:將嵌套結構傳遞給函式
