如何在函数重载中推导 lambda 的模板参数?

Sup*_*eto 0 c++ lambda c++17 function-templates-overloading

我应该如何修改我当前的函数签名

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)
Run Code Online (Sandbox Code Playgroud)

为了被调用

auto fSqrt = [](decltype(n) v) {return std::sqrt(static_cast<float>(v));};
std::cout<<(isPrime(n,fSqrt)?"Positive":"Negative")<<'\n';
Run Code Online (Sandbox Code Playgroud)

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 的正确语法是什么?
请帮助我。

Ruk*_*uks 6

问题在于默认参数不会有助于模板参数中类型的推导。

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

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
}
Run Code Online (Sandbox Code Playgroud)

在这种情况下,您需要做的是使用函数重载:

// ...

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

// ...
Run Code Online (Sandbox Code Playgroud)