Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

I don't see any way to express something like Option<Infallible> in C++

Regardless of "age of the project" or other considerations, this doesn't seem like a particularly tricky edge case of generic programming and yet C++ is stumped AFAICT



According[0] to Perplexity.ai, you could use std::optional<std::monostate> to get a C++ approximation of your Rust type.

I am neither an expert in modern C++ nor in Rust, but I have witnessed enough of C++'s evolution over time to know that if C++ language devs find a feature desirable enough they will do whatever it takes to frobnicate the language in order to claim support for that feature.

[0] https://www.perplexity.ai/search/is-it-possible-Sd3TML68TfKv...


std::monostate is a "unit type"[1]; there's only one value with with type monostate (the value is std::monostate{}), so all monostate values are equivalent.

Infalible is a "empty type"[2]; there are no values with type Infalible, so a value cannot be constructed, so Optional<Infalible> is always None, never Some(infallible). Importantly, the compiler knows this and can use it to reason about the correctness of code.

C++ has no empty types. Void is close, but it's sometimes used where a unit type would be used, and anyway it's not a first class type. For example, you can't use std::optional<void>. Even if it were possible to make an empty type in C++, it wouldn't give you anything, because the compiler isn't equipped to reason about them.

BTW, the rust equivalent to std::optional<std::monostate> is Optional<()>. The empty tuple is Rust's idomatic unit type.

[1]: https://en.wikipedia.org/wiki/Unit_type

[2]: https://en.wikipedia.org/wiki/Empty_type


While I watch with some desmay, one of favourite languages turning beyond PL/I levels of complexity, it isn't alone in this direction.

One of the reasons I am not able to follow up on C++ as much as I did in the past, isn't directly related to its complexity, rather that my main worktools, the JVM, CLR and Web ecosystems, are reaching similar levels of complexity, specially with the 6 months release candence, and there is only so much one can keep up with.


std::optional<std::monostate> has two values, Option<Infallible> has one, so by my counting that's a 100% error.

It is likely the best that can be done, but that's my point, C++ can't do this because the foundational type system isn't up to the task.


That wasn't really the point of my remark, rather C with Classes C++98 style with plenty of C style coding for strings and arrays (Roman Numerals), Modern C++ best pratices with safety tooling (Arabic Numerals).




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: