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?
priority_queue
is a template and it expects a type as an argument, where is binary_function
is a function object.
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...
精彩评论