Advertisement
Guest User

Unnamed Template Misparsing

a guest
Oct 31st, 2012
11
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. /*Write a class template that uses a vector to implement a stack data structure.*/
  2.  
  3. /*Modify your solution to the previous exercise so that the type of the container
  4.  used to implement the stack is a template template parameter.*/
  5. #include <vector>
  6. #include <iostream>
  7. #include <stdexcept>
  8.  
  9. using namespace std;
  10.  
  11. template<class T, template<class U, class = allocator<U> > class Cont>
  12. class Stack {
  13.   Cont<T> stack;
  14. public:
  15.   void push(const T& t);
  16.   void pop();
  17.   const T& top();
  18.   bool empty() { return stack.empty(); }
  19. };
  20.  
  21. template<class T, template<class U, class = allocator<U> > class Cont>
  22. void Stack<T,Cont>::push(const T& t) {
  23.  stack.push_back(t);
  24. }
  25.  
  26. template<class T, template<class U, class = allocator<U> > class Cont>
  27. void Stack<T,Cont>::pop() {
  28.   if (stack.empty() ) throw runtime_error("Stack empty");
  29.   stack.erase(stack.end()-1, stack.end());
  30. }
  31.  
  32. template<class T, template<class U, class = allocator<U> > class Cont>
  33. const T& Stack<T,Cont>::top() {
  34.   if ( stack.empty() ) throw runtime_error("Stack empty");
  35.   return *(stack.end()-1);
  36. }
  37.  
  38. int main(int argc, char**argv)
  39. {
  40.  Stack<int,vector> st;
  41.  st. push(1);
  42.  st.push(2);
  43.  st. push(3);
  44.  try {
  45.  while (!st.empty()) {
  46.    cout << st.top() << " ";
  47.    st.pop();
  48.  }
  49.  } catch (std::runtime_error& e) {
  50.   cout << e.what() << endl;
  51.  }
  52.  cout << endl;
  53.  return 0;  
  54. }
Advertisement
RAW Paste Data Copied
Advertisement