One can write a simple wrapper over STL's std::stack
and iterate over the underlying container since, quoting from the reference:
The container must satisfy the requirements of SequenceContainer
This container is accessible via the protected member c
, so something like this should probably work for your case:
#include <stack>
#include <iostream>
#include <iterator>
template <typename T, typename Container = std::deque<T>>
struct DebugStack : private std::stack<T, Container> {
auto& push(T& elem) {
std::stack<T>::push(elem);
return *this;
}
auto& push(T&& elem) {
std::stack<T>::push(elem);
return *this;
}
auto& pop() {
std::stack<T>::pop();
return *this;
}
T top() {
return std::stack<T>::top();
}
void print() {
auto const& container = std::stack<T>::c;
//T should be printable
std::copy(begin(container), end(container), std::ostream_iterator<T>(std::cout, " "));
std::cout<<'\n';
}
};
int main() {
{
DebugStack<int> stack;
stack.push(1).push(2).push(3).push(4);
stack.print();
stack.pop().pop().pop();
stack.print();
}
{
DebugStack<std::string> stack;
stack.push("First").push("Second").push("Third").push("Fourth");
stack.print();
stack.pop().pop().pop();
stack.print();
}
}
Output:
1 2 3 4
1
First Second Third Fourth
First
One can change the auto
return type to DebugStack
(as in here) to make this solution work with C++11
since auto deduction of return types was introduced with C++14
.