首页 > 解决方案 > 如何在函数重载中推断 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 的正确语法是什么?
请帮助我,请。

标签: c++lambdac++17function-templates-overloading

解决方案


问题是默认参数不会对模板参数中的类型进行推导。

这可以通过这个主要示例来展示:

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);
}

// ...

推荐阅读