【发布时间】:2023-02-25 17:41:10
【问题描述】:
预定义仿函数需要就地实例化(带空括号)以用于算法,但不能用作容器适配器(如 priority_queue)的类型参数。为什么不同?
#include <queue>
#include <vector>
#include <numeric>
int main(){
std::priority_queue<int, std::vector<int>,
// parentheses are NOT needed here: std::greater<>
std::greater<>> pq;
pq.push(1);
pq.push(2);
pq.push(3);
std::vector<int> v = {1, 2, 3};
auto result = accumulate(v.begin(), v.end(), 0,
// parentheses are needed here std::plus<>()
std::plus<>());
}
【问题讨论】:
-
因为模板形参表找的是类型,而函数形参表找的是对象。与您不写
std::max(7, int)的原因相同。