c++ - 如何在函数重载中推断 lambda 的模板参数?
问题描述
我应该如何修改我现在的函数签名
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 的正确语法是什么?
请帮助我,请。
解决方案
问题是默认参数不会对模板参数中的类型进行推导。
这可以通过这个主要示例来展示:
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);
}
// ...
推荐阅读
- php - Authorization methods only works for default guard in Laravel
- haskell - Haskell:将 Int 转换为长度为 n 的字符串
- vba - 将 Outlook.Items 对象限制为带有附件的电子邮件
- c++ - 如何在 QT 中捕获“没有应用程序注册为处理此文件”?
- codeigniter - 如何处理指向我的服务器的 CNAME 记录
- python - Python Dataframe 遍历行(比较它们之间的值)并准备一个组作为输出
- node.js - mongodb、mongoose、express、nodejs 使用旧值更新多个文档中的字符串
- python - 为什么 python 包中 __init__.py 中的命令行为与命令行不同?
- android - 如何在不使用 FFMPEG 重新编码的情况下在精确位置修剪视频文件
- android - 无法构建项目 java.lang.NoClassDefFoundError: javax/xml/bind/JAXBException