0

Predefined functors need to be in-place instantiated (with empty parentheses) for use in algorithms but not as type parameters for container adapters such as priority_queue. Why the difference?

#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<>());
}
Aamir
  • 1,974
  • 1
  • 14
  • 18
Mikhail
  • 173
  • 6
  • 1
    Because the template parameter list is looking for a type, and the function parameter list is looking for an object. Same reason you wouldn't write `std::max(7, int)`. – Nathan Pierson Feb 24 '23 at 17:18

2 Answers2

4

std::priority_queue is a class template with type template parameters. Its specialization requires to specify type template arguments. And std::greater<> is a type used as a type template argument.

On the other hand, in an algorithm you need to supply a functional object as for example std::greater<>().

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
1

In both cases the type of the callable is a template argument. For the std::priority_queue you explicitly state the template argument, a type. With std::accumulate you pass an instance of the comparator such that the template arugment (the type of the comparator can be deduced).

With CTAD (class template argument deduction) this difference is less pronounced. If you want you can put it the other way around:

#include <numeric>
#include <queue>

int main() {
    std::priority_queue pq(std::greater<int>{},std::vector<int>{});
    
    std::vector<int> x;
    std::accumulate<std::vector<int>::iterator,int,std::greater<>>(x.begin(),x.end(),0,{});
}

Here, I made use of CTAD to let the constructor deduce the type of the argument passed to the constructor. Then with std::accumulate, its rather uncommon, but if you like you can explicitly specify tempalte arguments for the algorithm. Though you still need to pass a default constructed instance, because there is no overload with a default for the binary operation (there could be, its just not that useful, because usually you want to write just std::accumulate(..) and have all template arguments be deduced).

463035818_is_not_an_ai
  • 109,796
  • 11
  • 89
  • 185