Stack Template Arguments

Focus on template arguments

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

stack<int, vector<int>> myStack;

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

stack<int, vector<string>> myStack;

Note that I declare that the stack contains type elements int, but at the same time, I declare that the underlying data structure contains elements string.

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

+4
source share
3 answers

What you do is undefined behavior. However, I am going to explain why this works fine.

std::stack<T, TContainer> , , . .

, , - std::stack::value_type. std::stack::push :

void push( const value_type& value );

, :

using value_type = typename TContainer::value_type

, , , , TContainer! vector<string>::value_type, value_type string. , T, int , . , .

, , :

undefined, T Container:: value_type. ( ++ 17)

.

+6

:

T - . undefined, T Container:: value_type. ( ++ 17)

Undefined , , .

, , .

+1

, , int Container::value_type.

++ 17, . .

:

#include <stack>
#include <string>
#include <vector>

int main() {
    std::stack<int, std::vector<std::string>> s;
    s.push(3);
}

Unable to compile under OS X (clang, libC ++, C ++ 11) with:

blah.cc:7:7: error: no matching member function for call to 'push'
    s.push(3);
    ~~^~~~
/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/../include/c++/v1/stack:194:10: note: 
      candidate function not viable: no known conversion from 'int' to 'const value_type' (aka
      'const std::__1::basic_string<char>') for 1st argument
    void push(const value_type& __v) {c.push_back(__v);}
         ^
/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/../include/c++/v1/stack:197:10: note: 
      candidate function not viable: no known conversion from 'int' to 'value_type' (aka 'std::__1::basic_string<char>') for
      1st argument
    void push(value_type&& __v) {c.push_back(_VSTD::move(__v));}
         ^
1 error generated.
0
source

Source: https://habr.com/ru/post/1650416/


All Articles