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.
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.
template <typename T>
class Option {
private:
uint8_t _storage [sizeof (T)];
T * _embedded;
public:
Option () : _embedded (nullptr) {
}
Option (const T & obj) : _embedded (new (_storage) T (obj)) {
}
Option (const Option<T> & other)
: _embedded (
other->_embedded ? new (_storage) T (other->_embedded) : nullptr
) {
}
// ...
~Option () {
if (_embedded) _embedded->~T ();
}
};