Hedede Hedede - 4 months ago 8
C++ Question

Why std::stack does not use template template parameter

Why std::stack and std::queue use type template parameter instead template template parameter for underlying container type?

I.e. why is stack declared like this:

template<typename T, typename Container = deque<T>>
class stack;


but not like this:

template<typename T, template<typename> class Container = deque>
class stack;


?

Answer

Because typically containers like std::vector have more than one template argument. By not caring about it being a template, you allow every kind of container to be used.

How would

template<class T, class Allocator = std::allocator<T>> class vector;

fit onto

template<typename> class Container

as you would have it in your stack? Hint it doesn't! You'd need special cases for each number of template arguments you'd want to support, which is silly, because these typically don't contribute any more information than a simple

typename Container

Note that to get at the actual template arguments of e.g. a std::vector, you have the typedefs std::vector::value_type and std::vector::allocator_type, removing the need of having these types available explicitly where you actually use the type (i.e. the Container of stack).

Comments