Advertisement
Guest User

Bad Example Of C++ Cons List

a guest
Mar 25th, 2017
116
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.80 KB | None | 0 0
  1. template<class T> class List
  2. {
  3. private:
  4.  
  5.     enum class CtorType { Empty, Cons };
  6.  
  7.     union U
  8.     {
  9.         struct Cons { T item; List<T> * next; } cons;
  10.         struct Empty {} empty;
  11.     };
  12.  
  13.     CtorType type;
  14.  
  15.     U constructor;
  16.    
  17.     List(void)
  18.         : type(CtorType::Empty), item(), next(nullptr)
  19.     {}
  20.    
  21.     List(const T & item, const List<T> & next)
  22.         : type(CtorType::Cons), item(item), next(&next)
  23.     {}
  24.  
  25. public:
  26.  
  27.     bool IsEmpty()
  28.     {
  29.         return this->type == CtorType::Empty;
  30.     }
  31.  
  32.     T Head()
  33.     {
  34.         switch(this->type)
  35.         {
  36.             case CtorType::Ctor: return this->constructor.cons.item;
  37.             default: assert(false, "Attempt to get Head on empty list");
  38.         }
  39.     }
  40.  
  41.     static List<T> CreateEmpty()
  42.     {
  43.         return List<T>();
  44.     }
  45.  
  46.     static List<T> CreateCons(const T & item, const List<T> & next)
  47.     {
  48.         return List<T>(item, next);
  49.     }
  50. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement