C+ selective predefined functor initializaiton

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 neded 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<>());
}

>Solution :

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<>().

Leave a Reply