Std :: experimental :: optional <T> implementation: Constexpr constructor confusion
While the implementation of std::experimental::optional
( cppreference.com ) was confused by the specification of a specific constructor, namely:
constexpr optional( const T& value ); // (4)
( Source )
This constructor allows optional<T>
for the trivially destructible type T
in the context of constexpr
. While the first requirement, namely, to disable the user-supplied destructor in this case, in order to make optional<T>
alphabetic type, needs to be decided, I donβt know how to get around the restriction of placement-new, which is not allowed in constexpr .
It seemed to me that I should use optional<T>
with std::aligned_storage<T>
so that the types T
not constructive by default and satisfy any alignment requirements, if applicable. But, as I said, constexpr
forbids me to use a new placement in this particular constructor.
I had a lot of coffee and I donβt see the obvious solution here?
thanks
I do not know how to get around the placement constraint - new is not allowed in constexpr.
This is the correct diagnostic, literal type, constexpr
and new expressions do not mix. The easiest way to fulfill the various requirements of std::experimental::optional<T>
is to implement it with options. Positively, a union
should be involved at some point. Quick sketch:
template<typename Val> struct optional { union { Val optional_value; unsigned char dummy_byte; }; bool filled; // post-condition: no-value state constexpr optional() : dummy_byte {} , filled(false) {} // post-condition: has-value state constexpr optional(Val const& val) : optional_value(val) , filled(true) {} // other special members omitted for brevity };
In fact, in the old series of optional
sentences used for there is a paragraph on the method to demonstrate that the requirements put forward by it were reasonable in general. (Currently, std::experimental::optional
lives in various TS candidates for the libraryβs fundamental funds.)