比较
-
template <class T> struct greater;
std::greater
是一个类模板;std::greater<int>
是该类模板的一个实例,是一个类类型;std::greater<int>()
是该类类型的一个实例,是一个未命名的临时对象,其中()
是在调用类std::greater<int>
的构造函数,生成一个临时对象。
函数模板与类模板
- 函数模板允许隐式地推断模板参数类型,即通过函数调用时的实参来推断模板参数类型,而无需在
<>
中显式指定模板参数类型:-
template <class RandomAccessIterator, class Compare> void sort (RandomAccessIterator first, RandomAccessIterator last, Compare comp);
- 对一个
vector<int> a = {5, 3, 6, 1, 7}
进行降序排序,以下调用是等价的:sort<vector<int>::iterator, greater<int>>(a.begin(), a.end(), greater<int>());
显示指定模板参数类型sort(a.begin(), a.end(), greater<int>());
隐式参数类型推断
-
- 类模板则不支持隐式参数类型推断,需要在
<>
中显示地指出模板参数类型:-
template <class T, class Container = vector<T>, class Compare = less<typename Container::value_type> > class priority_queue;
priority_queue<ListNode*, vector<ListNode*>, comp> que;
- 其中,comp 为一个函数对象类型(重载了调用运算符
operator()
的类);-
struct comp { bool operator()(ListNode* a, ListNode* b) { return a->val > b->val; } };
-
- 这里,模板参数 Compare 为类型
comp
,而不是一个对象comp()
;
- 其中,comp 为一个函数对象类型(重载了调用运算符
-
结论
sort(a.begin(), a.end(), greater<int>());
greater<int>()
有括号()
,是对象,是函数实参,利用了隐式模板参数推断;
priority_queue<ListNode*, vector<ListNode*>, comp> que;
comp
无括号,是类型,是模板实参;