如果使用不满足所需底层容器要求的容器创建stack
,则会得到编译错误。这是如何在编译时和运行时确定的错误?
例如:
#include <iostream>
#include <stack>
using namespace std;
class Test {
int data;
};
int main()
{
stack<int, Test> s;
// s.push(5);
cout<<"Hello World";
return 0;
}
将返回编译错误:
In file included from /usr/include/c++/6/stack:61:0,
from main.cpp:10:
/usr/include/c++/6/bits/stl_stack.h: In instantiation of ‘class std::stack<int, Test>’:
<span class="error_line" onclick="ide.gotoLine('main.cpp',20)">main.cpp:20:22</span>: required from here
/usr/include/c++/6/bits/stl_stack.h:102:46: error: no type named ‘value_type’ in ‘class Test’
typedef typename _Sequence::value_type _Sequence_value_type;
^~~~~~~~~~~~~~~~~~~~
/usr/include/c++/6/bits/stl_stack.h:124:61: error: no type named ‘value_type’ in ‘class Test’
typedef typename _Sequence::value_type value_type;
^~~~~~~~~~
/usr/include/c++/6/bits/stl_stack.h:125:61: error: no type named ‘reference’ in ‘class Test’
typedef typename _Sequence::reference reference;
^~~~~~~~~
/usr/include/c++/6/bits/stl_stack.h:126:61: error: no type named ‘const_reference’ in ‘class Test’
typedef typename _Sequence::const_reference const_reference;
^~~~~~~~~~~~~~~
/usr/include/c++/6/bits/stl_stack.h:127:61: error: no type named ‘size_type’ in ‘class Test’
typedef typename _Sequence::size_type size_type;
^~~~~~~~~
我希望能够执行模板类型的需求,我希望使用std::stack
如何作为参考。
std::stack
实际上没有做任何事情。std::stack
内部有一个like like
using value_type = Container::value_type;
和您的情况,Container
是Test
,因为Test::value_type
不存在,你得到一个编译器错误。