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

时间:2019-10-18 03:24:41

标签: c++ templates callable function-templates default-arguments

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

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()的含义,如果我将自己的比较函数传递给模板,则该模板有效,它如何从函数中推断出F

1 个答案:

答案 0 :(得分: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