Optional

Files CCore/inc/Optional.h CCore/src/Optional.cpp

The class Optional is a polymorphic collection of objects. It has number of object slots. Each slot can be occupied by an object of any type. Once created, the object occupies the slot until the Optional object is destroyed.


class Optional : NoCopy
 {
   ....

  public:
 
   explicit Optional(unsigned max_slot);
   
   ~Optional();
   
   template <unsigned slot,class T>
   T * try_take();
   
   template <unsigned slot,class T>
   T * take();
 };

The constructor argument is a maximum slot number. I.e. the valid slot numbers are [0,max_slot].

try_take() returns the pointer to the object at the given slot, if any. If there is no object, the null pointer is returned.

take() returns the pointer to the object at the given slot. If there is no object, it is created using the default constructor. An exception may be thrown in case of error.

Make sure, you always use the same type for the same slot. It is better to hide the Optional object behind some facade class:


class OptData
 {
   Optional opt;

  public:

   OptData() : opt(99) {}

   ~OptData() {}

   unsigned * try_take_counter() { return opt.try_take<0,unsigned>(); }

   unsigned * take_counter() { return opt.take<0,unsigned>(); }

   DynArray<int> * try_take_buf() { return opt.try_take<1,DynArray<int> >; }

   DynArray<int> * take_buf() { return opt.take<1,DynArray<int> >; }

   ....
 };

Internally, Optional is a radix tree. So its access methods are fast, but not extremely fast.