3

Why can I do this:

stable_sort(it1, it2, binary_function);

but not this:

priority_queue<type, vector<type>, binary_function> pq;

Why can I use a function in the first case, but need an object in the second?

Baruch
  • 20,590
  • 28
  • 126
  • 201

2 Answers2

3

priority_queue is a template and it expects a type as an argument, where is binary_function is a function object.

Kirill V. Lyadvinsky
  • 97,037
  • 24
  • 136
  • 212
1

If you check out the reference on std::stable_sort, you will see that the binary_function you provided, should be a function object as well... There is no difference between the two, except that maybe in the second case there is no proper "cast" or conversion made from a function to a proper function object.

I believe this may be due to the fact that *sort functions use the functor directly, and immediately, thus if the function address is valid when the *sort function is called, it will be valid for the duration of the function call. When creating a container that uses this as a data member (in essence), you can't be sure the function reference will become invalidated during the lifetime of the container object. I know it's a loose handwaving explication, but it's the best I can come up with. Perhaps in C++ the reference to a binary function will be implicitely converted to the construction of a std::function so that the function is "copied" and there is no validity problem.

I hope I haven't lost you now...

rubenvb
  • 74,642
  • 33
  • 187
  • 332
  • In the first case, `binary_function` is the name of an instance of a function object or the name of a function. As such it cannot be used in the second case where the template parameter has to be a type name (not a variable/function name). – visitor Dec 15 '10 at 14:27
  • A function object is a class nonetheless, right? Something like a struct with `bool operator( arg )`. Otherwise it's just an address of a function, which can also be used of course, but not in this case IMHO (due to unknown lifetime issues of that reference) – rubenvb Dec 15 '10 at 14:34
  • There's a difference between a class and an instance of this class. `MyFunctor fun;` - `MyFunctor` is the name of the class and `fun` is the name of the instance. `stable_sort` takes `fun` (deducing the type of the argument) and priority_queue's template argument takes `MyFunctor` – UncleBens Dec 15 '10 at 16:01