If you create a stack
with a container that doesn't meet the requirements of the required underlying container, you get a compile error. How is this an error that can be determined at compile-time vs. run-time.
For example:
#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;
}
Will return the compile errors:
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;
^~~~~~~~~
I wanted to be able to enforce requirements for a template type and I was hoping to use how std::stack
does it as a reference.
stl
vsstd
. Just corrected it.static_assert
with<type_traits>
library, ...), but sometimes you can just go with "I assume typeT
will have these members available for me" and let the compiler detect any issues.