Ahmad Jamal Mughal Ahmad Jamal Mughal - 4 months ago 7
C++ Question

Stack Template Arguments

Focus on the template arguments



I can create a stack (an adapter class template from standard library) object like this,

stack<int, vector<int>> myStack;


I know the second template argument means the underlying data structure of the stack. But why the following line doesn't give a compile time error?

stack<int, vector<string>> myStack;


Notice that I'm declaring a stack to contain elements of type
int
, but at the same time I'm declaring the underlying data structure to hold
string
elements.

Functionally, It works as if it was a stack of string elements.

Answer

What you are doing is undefined behaviour. Nevertheless, I am going to explain why it seems to work fine.

The container adapter std::stack<T, TContainer> contains several type symbols that are aliases for types that will be commonly used. There is a list here.

One that concerns us here is std::stack::value_type. It basically determines what type the methods std::stack::push and friends expect:

void push( const value_type& value );

We can also see how it is defined:

using value_type = typename TContainer::value_type

So, the type that is used in all actions is actually only based on the second type, TContainer ! In your case, that is vector<string>::value_type, so value_type will be an alias to string. The type used for T, int in your case, is not used. Thus, everything seems to work.

But even though this works in your case with your particular compiler, it is actually not allowed:

The behavior is undefined if T is not the same type as Container::value_type. (since C++17)

You can find the source for this quote here.