可调用对象作为默认模板参数
Callable object as default template argument
我在书上读了一些关于默认模板参数的内容,这段代码让我真的很困惑
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
相关文章:
- 使函数参数默认为周围范围
- 如何将值传递给其参数(默认参数)
- 当“std::make_index_sequence”和“std::index_sequence”用于模板参数默认类型时
- C ,构造器中允许的参考参数默认值
- 哪些规则控制参数默认赋值?
- 错误:上一个规范后给出的参数默认参数
- 是否可以设计一个包含模板参数默认值的类
- 构造函数中参数C++默认值
- 如何设置依赖于其他参数的参数默认值
- C++模板参数默认函数实现
- QInput对话框参数默认值
- g++4.8.2上列表方法参数默认初始化时出错
- 在函数定义中指定参数默认值会导致错误 C2143:语法错误:'='之前缺少')'
- 函数模板:将第一个模板参数默认为第二个
- 模板模板参数默认可以引用其他模板类型的参数
- 参数默认为先例参数的值
- 如何修改一个类,使它只有一个成员函数,所有参数默认
- 内置类型的模板参数默认值
- 是否可以使用构造函数或对象作为其他类方法的参数默认值?
- 模板参数默认为更高版本