title: Option/Maybe class for C++
body: <p>I would like to implement a Scala-like Option / Haskell-like Maybe class in C++. For efficiency reasons, I do not want to use dynamically allocated memory, nor do I want to use polymorphism. In addition, I do not want any object of the embedded type to be created if the Option is None.</p>
  
  <p>Can anybody tell me whether the following approach may cause problems? I have to statically allocate memory for the embedded object within my Option class, but I cannot define a member field of the embedded type, since this would be initialized on creation of the Option object even if the Option is None.</p>
  
  <pre><code>template &lt;typename T&gt;
  class Option {
  private:
      uint8_t _storage [sizeof (T)];
      T * _embedded;
  public:
      Option () : _embedded (nullptr) {
      }
  
      Option (const T &amp; obj) : _embedded (new (_storage) T (obj)) {
      }
  
      Option (const Option&lt;T&gt; &amp; other)
      : _embedded (
          other-&gt;_embedded ? new (_storage) T (other-&gt;_embedded) : nullptr
      ) {
      }
  
      // ...
  
      ~Option () {
          if (_embedded) _embedded-&gt;~T ();
      }
  };
  </code></pre>