Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Stack Template Arguments

Tags:

c++

c++11

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.

like image 671
Ahmad Jamal Mughal Avatar asked Mar 11 '23 12:03

Ahmad Jamal Mughal


2 Answers

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.

like image 187
nshct Avatar answered Mar 20 '23 16:03

nshct


From the documentation:

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

Undefined behaviour means it might compile, it might even work, or it might wipe your hard drive.

How it fails, if it does, is implementation dependant.

like image 35
1stCLord Avatar answered Mar 20 '23 17:03

1stCLord