top | item 41036074

(no title)

tpolzer | 1 year ago

What's really weird to me is not that C++ has a unit type and picked a weird name for it (that's just C++). The weird thing is how many unit types it has:

- std::nullopt_t

- std::nullptr_t

- std::monostate

- std::tuple<>

And I'm sure there's more.

discuss

order

omnicognate|1 year ago

The distinct types are the whole point. You wouldn't want a std::tuple<> to be implicitly convertible to a std::optional<T> (for arbitrary T), and std::nullptr_t exists to be the type of nullptr, which captures the conversion behaviours appropriate for null pointer literals and has nothing to do with the variant use case std::monostate exists to serve.

tpolzer|1 year ago

If there was a std::unit_t and it was implicitly convertible to optional, tuple and pointer, I don't think that would be worse in terms of usability at all (maybe worse in readability for people who haven't heard of a 'unit' type).

As for the std::variant use case, using std::monostate is only a matter of convention there. You could use any of the other unit types just the same.

mmaniac|1 year ago

Why wouldn't you want std::tuple<> to be the same as std::monostate, though? In many languages with a proper unit type such as Haskell and Rust, the zero tuple is the unit type.

bombela|1 year ago

What about "void"?

tines|1 year ago

void isn’t a unit type (inhabited by a single value), it’s a “bot” type, I.e. no values inhabit it.