I came across this piece of code in cpp ref
template<
class T,
class Container = std::vector<T>,
class Compare = std::less<typename Container::value_type>
> class priority_queue;
What exactly is the purpose of using typename Container::value_type
in the above declaration? Will the following not work?
template<
class T,
class Container = std::vector<T>,
class Compare = std::less<T>
> class priority_queue;
This is to be more generic: Container
is a parameter and it might be a container (parametrized on T
) whose value_type
is different from T
. From the top of my head I dont know a good example, but naively there is also no reason to put that constraint on the used Container
(ie value_type
must be T
in your version).
For the sake of the example, lets say you have a strange_container
whose value_type
is std::pair<T,T>
and you want to instantiate the template with
priority_queue<T,strange_container<T>>
then your default Compare = std::less<T>
wouldnt work with that container, while Compare = std::less<typename Container::value_type>
would correctly compare pairs.
Note that the above doesnt apply since C++17, as (from cppref):
The behavior is undefined if T is not the same type as Container::value_type. (since C++17)
So it seems like the signature was choosen with maximum genericity in mind and only later it was realized that this degree of freedom wasnt the best choice. And actually there are good reasons to require value_type
and T
to be the same, see eg here for more on this.