Playing with templates

Dumb strokes of C++ templates while bored generated this templated queue.

  1. #define QueueSize 5
  2.  
  3. template <typename T>
  4. class Queue
  5. {
  6.  
  7. public:
  8. Queue() : head(NULL), tail(-1) { for (int i=0; i < QueueSize; queue[i++]=NULL); }
  9. void insert(T in);
  10. bool isEmpty() { return ( queue[head] == NULL ) ? true : false; }
  11. bool isFull() { return (head == tail && queue[head] != NULL) ? true : false; }
  12. T remove();
  13. void showContents();
  14.  
  15. private:
  16. T queue[QueueSize];
  17. int head, tail;
  18.  
  19. };
  20.  
  21. template <typename T>
  22. void Queue<T>::showContents()
  23. {
  24.  
  25. int loc=0, i=0;
  26.  
  27. if(isEmpty())
  28. {
  29. cout << "Empty" << endl;
  30. return;
  31. }
  32.  
  33.  
  34. for (i=head; i < tail || i < QueueSize; i++)
  35. cout << queue[i] << " ";
  36.  
  37. if(head > loc)
  38. while(loc < tail && loc < head && queue[loc] != NULL)
  39. cout << queue[loc++] << " ";
  40.  
  41. cout << endl;
  42.  
  43.  
  44. }
  45.  
  46.  
  47. template <typename T>
  48. T Queue<T>::remove()
  49. {
  50. int retVal = 0;
  51.  
  52. if (!isEmpty())
  53. {
  54.  
  55. retVal = queue[head];
  56. queue[head] = NULL;
  57.  
  58. if (head == QueueSize - 1)
  59. head = 0;
  60. else
  61. head++;
  62.  
  63. }
  64. else
  65. cout << "Stack Underflow" << endl;
  66.  
  67. return retVal;
  68.  
  69. }
  70.  
  71. template <typename T>
  72. void Queue<T>::insert(T in)
  73. {
  74. int prevTail = tail;
  75.  
  76. if (tail == QueueSize - 1)
  77. tail = 0;
  78. else
  79. tail++;
  80.  
  81.  
  82. if (isFull())
  83. {
  84. cout << "Stack Overflow" << endl;
  85. tail = prevTail;
  86. }
  87. else
  88. queue[tail] = in;
  89.  
  90.  
  91. return;
  92. }

Tags: