Is this an appropriate use of std::optional?

Hi

I have a container class along the following lines:

1
2
3
4
5
6
7
8
9
10
11
12
13
template <class T>
class Container
{
   public:
      void addElement(int id, T t)
      {
           mContainer.insert(std::pair<int,T>(id,t));
      }

   private:
      std::map<int, T> mContainer;

};


In most cases, the client using the Container class would supply an ID and an associated object (the templated type for the class). However, in some cases the user may wish to supply an id without an associated object (the id would be used by other components of the Container class not detailed above):

1
2
3
4
       void addElement(int id)
      {
           // ?????
      }


I am thinking about the best way of representing this. As I see it, this could be done in the following ways:
(1) Using std::optional so that the mapped value either stores type T (if supplied by the client) or "nothing":

 
      std::map<int, std::optional<T>> mContainer;


(2) Mapped value is a smart pointer to a dynamically generated T. If the client does not supply T then the smart pointed would be set to null.

 
      std::map<int, std::unique_ptr<T>> mContainer;


Which of the above options do you think would be better? Is there another option which is not set out above?

Thanks
Last edited on
I think option one is the best choice.
The interface is appealing:
 
void addElement(int id, std::optional<T> x) { mContainer[id] = std::move(x); }

Additionally, it doesn't incur pointless memory allocations.
Last edited on
Topic archived. No new replies allowed.