cpp_weekly icon indicating copy to clipboard operation
cpp_weekly copied to clipboard

Insight of std::optional vs std::variant

Open toRatnesh opened this issue 1 year ago • 6 comments

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?

toRatnesh avatar May 30 '23 15:05 toRatnesh

One could argue that:

void foo(std::optional<int> a);

is more clear than

void foo(std::variant<int> a);

fcolecumberri avatar May 30 '23 16:05 fcolecumberri

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.

LB-- avatar May 31 '23 19:05 LB--

Thus std::variant<int> is impossible to be in any state other than having an int value.

It's possible, with an UDT that converts to int, but throws an exception in the conversion function.

JohelEGP avatar May 31 '23 19:05 JohelEGP

@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.

LB-- avatar May 31 '23 19:05 LB--

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 avatar May 31 '23 19:05 JohelEGP

@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.

LB-- avatar May 31 '23 19:05 LB--