可调用对象作为默认模板参数

问题描述 投票:1回答:1

我在书上读了关于默认模板参数的东西,这段代码让我感到非常困惑

template<typename T, typename F = less<T>>
bool compare(const T& v1, const T& v2, F f = F())
{
    return f(v1, v2);
}

书中说F代表可调用对象的类型,并将f绑定到该对象。但是F怎么可能是这种类型?

我不了解F f=F()的含义,如果我将自己的比较function传递给模板,它可以工作,如何从函数中推导出F

c++ templates callable function-templates default-arguments
1个回答
1
投票

我不理解F f=F() [...]的含义>

这是为C ++中的函数参数提供default argument的方式。就像我们一样,任何正常的功能;假设

void func1(int i = 2)     {/*do something with i*/}
//         ^^^^^^^^^
void func2(int i = int()) {/*do something with i*/}
//         ^^^^^^^^^^^^^
void func3(int i = {})    {/*do something with i*/}
//         ^^^^^^^^^^

允许使用参数调用上述函数

func1(1); //---> i will be initialized to 1
func1(2); //---> i will be initialized to 2
func1(3); //---> i will be initialized to 3

或不提供参数。

func1(); //---> i will be initialized to 2
func2(); //---> i will be initializedto 0
func3(); //---> i will be initialized to 0

compare的相似方式也可以不使用第三个参数,例如

compare(arg1, arg2) // ---> f will be `std::less<T>` here, which is the default argument

或带有第三个参数

compare(arg1, arg2, [](const auto& lhs, const auto& rhs){ return /*comparison*/;});
//                  ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ some comparison function here
© www.soinside.com 2019 - 2024. All rights reserved.