cpp_weekly
cpp_weekly copied to clipboard
Insight of std::optional vs std::variant
Why std::optional is not a variadic template like std::variant? If I use std::variant with a single type will it be same as std::optional?
if variadic std::optional will be same as std::variant? if yes, why do we need std::optional instead of std::variant?
One could argue that:
void foo(std::optional<int> a);
is more clear than
void foo(std::variant<int> a);
std::variant
's empty state is difficult to manufacture, as it can only be done if constructing the contained type throws an exception. Thus std::variant<int>
is impossible to be in any state other than having an int
value.
Thus
std::variant<int>
is impossible to be in any state other than having anint
value.
It's possible, with an UDT that converts to int
, but throws an exception in the conversion function.
@JohelEGP Can you provide a demo of that? It sounds like something you'd have to go out of your way to try and do using emplace
or std::in_place_type
/std::in_place_index
, and even then I think it might be possible/allowed for an implementation to harden itself against that.
https://en.cppreference.com/w/cpp/utility/variant/valueless_by_exception has an example of that.
and even then I think it might be possible/allowed for an implementation to harden itself against that.
It seems like they do that today: https://compiler-explorer.com/z/o8hPsr5hz.
@JohelEGP So then my point stands, it is difficult and sometimes impossible to create a valueless std::variant
.
I think the discussion is better when comparing std::optional<T>
to std::variant<std::monostate, T>
- one implies the presence or absence of a value, while the other implies two valid states where one doesn't necessitate additional information.