【问题标题】:How to deduce template argument for lambda, in function overload?如何在函数重载中推断 lambda 的模板参数?
【发布时间】:2021-10-28 06:07:38
【问题描述】:

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

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&amp; a,const TypeData&amp; b) {return a%b==0;} 一切都很好。

传递默认 lambda 的正确语法是什么?
请帮帮我。

【问题讨论】:

  • 如果一个模板参数有一个默认参数,那么它后面的所有参数也必须有默认参数。

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


【解决方案1】:

问题在于默认实参对模板形参类型的推导没有贡献。

这可以用这个主要的例子来展示:

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

// ...

【讨论】:

    【解决方案2】:

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

    【讨论】:

      【解决方案3】:

      你需要为你的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) {
        // ...
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2018-04-25
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多