I am trying to write a function that can print both stack and queue, my code is as following
template<typename Cont>
void print_container(Cont& cont){
while(!cont.empty()){
if(std::is_same<Cont, stack<int>>::value){
auto elem = cont.top();
std::cout << elem << '
';
} else {
auto elem = cont.front();
std::cout << elem << '
';
}
cont.pop();
std::cout << elem << '
';
}
}
int main(int argc, char *argv[])
{
stack<int> stk;
stk.push(1);
stk.push(2);
stk.push(3);
queue<int> q;
q.push(1);
q.push(2);
q.push(3);
std::cout << "print stack" << endl;
print_container(stk);
std::cout << "print queue" << endl;
print_container(q);
return 0;
}
But it doesn't work here, the error info is:
demo_typeof.cpp:35:30: error: no member named 'front' in 'std::__1::stack<int, std::__1::deque<int, std::__1::allocator<int> > >'
auto elem = cont.front();
~~~~ ^
demo_typeof.cpp:52:5: note: in instantiation of function template specialization 'print_container<std::__1::stack<int, std::__1::deque<int, std::__1::allocator<int> > > >' requested here
print_container(stk);
^
demo_typeof.cpp:32:30: error: no member named 'top' in 'std::__1::queue<int, std::__1::deque<int, std::__1::allocator<int> > >'
auto elem = cont.top();
~~~~ ^
demo_typeof.cpp:54:5: note: in instantiation of function template specialization 'print_container<std::__1::queue<int, std::__1::deque<int, std::__1::allocator<int> > > >' requested here
print_container(q);
^
2 errors generated.
I know it's problematic, and know C++ is statically typed and without too much Runtime support. but I am wondering the specific reason why this doesn't work, and how to deal with it.
P.S.: The actual meaning of judge the typing of a container is that: You can simply change a DFS function into BFS by passing a queue container instead of a stack. So, BFS and DFS can share most of the code.
P.P.S: I am in C++ 11 environment, but answers for older or later standard are also welcomed.
Question&Answers:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…