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

Callable object as default template argument

本文关键字:参数 默认 调用 对象      更新时间:2023-10-16

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

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

我不明白F f=F()的含义 [...]

这就是C++中为函数参数提供默认参数的方式。就像我们一样,任何正常功能;比方说

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