115 points · by luu · 2y ago · 176 comments
I would've thought that the C++ template class would be just a marker interface to use on a monostate, so that users of the class know that it has shared state. But it seems like usage patterns in the article are very different from that, and all the comments here are ignorant of the history of the monostate pattern and befuddled at its intended usage. Maybe it was added to the standard by someone familiar with the design pattern, but they didn't do a good job with education and documentation to explain to everyone else what it was for?
[0] https://wiki.c2.com/?MonostatePattern
(originally discussed in http://ftp.math.utah.edu/pub/tex/bib/cppreport.html#White:19...)
> I would've thought that the C++ template class would be just a marker interface to use on a monostate, so that users of the class know that it has shared state.
Also, if that's what they really meant then they surely could've have written a far sorter comment that simply says this name is already taken and it should be called something else. They don't seem to be saying that at all.
(Not that it affects my original point, but FWIW that linked meaning of monostate isn't common in my experience, and it sounds like a truly awful idea: if your state is really good then be honest about it and use free functions. So it hardly seems worth reserving a useful word for it over the concept std::monostate is actually about.)
DonHopkins 85 days ago | parent | context | favorite | on: What if null was an Object in Java?
Why stop at null, when you can have both null and undefined? Throw in unknown, and you've got a hat trick, a holy trinity of nothingness! Of course the Rumsfeld Matrix further breaks down the three different types of unknowns.
https://en.wikipedia.org/wiki/There_are_unknown_unknowns
>"Reports that say that something hasn't happened are always interesting to me, because as we know, there are known knowns; there are things we know we know. We also know there are known unknowns; that is to say we know there are some things we do not know. But there are also unknown unknowns—the ones we don't know we don't know. And if one looks throughout the history of our country and other free countries, it is the latter category that tends to be the difficult ones." -Donald Rumsfeld
1) Known knowns: These are the things we know that we know. They represent the clear, confirmed knowledge that can be easily communicated and utilized in decision-making.
2) Known unknowns: These are the things we know we do not know. This category acknowledges the presence of uncertainties or gaps in our knowledge that are recognized and can be specifically identified.
3) Unknown unknowns: These are the things we do not know we do not know. This category represents unforeseen challenges and surprises, indicating a deeper level of ignorance where we are unaware of our lack of knowledge.
And Microsoft COM hinges on the IUnknown interface.
https://en.wikipedia.org/wiki/Tony_Hoare#Research_and_career
>Speaking at a software conference in 2009, Tony Hoare apologized for inventing the null reference:
>"I call it my billion-dollar mistake. It was the invention of the null reference in 1965. At that time, I was designing the first comprehensive type system for references in an object oriented language (ALGOL W). My goal was to ensure that all use of references should be absolutely safe, with checking performed automatically by the compiler. But I couldn't resist the temptation to put in a null reference, simply because it was so easy to implement. This has led to innumerable errors, vulnerabilities, and system crashes, which have probably caused a billion dollars of pain and damage in the last forty years." -Tony Hoare
https://news.ycombinator.com/item?id=19568378
>"My favorite is always the Billion-Dollar Mistake of having null in the language. And since JavaScript has both null and undefined, it's the Two-Billion-Dollar Mistake." -Anders Hejlsberg
>"It is by far the most problematic part of language design. And it's a single value that -- ha ha ha ha -- that if only that wasn't there, imagine all the problems we wouldn't have, right? If type systems were designed that way. And some type systems are, and some type systems are getting there, but boy, trying to retrofit that on top of a type system that has null in the first place is quite an undertaking." -Anders Hejlsberg
Assuming these mistakes are additive and not multiplicative.
`unknown` is a top type, since we're on the topic of nothingness it'd be remiss to not mention its dual, `never`.
The pair is also called `Any` and `Nothing` in some other languages.
Numbers use = if you don't care about type. For instance, the real number 0 and the complex number 0 + 0i would be treated equal by this function.
Do you care about strict pointer equality? eq.
Do you want to distinguish 0 and 0d0? eql.
Do you care about isomorphism? equal.
The only weird function to me would be equalp, given that it performs case-insensitive comparison of characters etc. Overall, I find complaints about the equality predicates to be based on a misunderstanding of the definition of "equality".
Clojure goes the opposite direction and has a single = function that performs all sorts of reflection and deep comparisons; it's convenient in practice, but it's also easy to burn CPU cycles if you are e.g. comparing large collections and only care about pointer equality.
It's more that LISP is the only language I know that exposes how complex the concept of equality actually is. All the other ones I use more-or-less make an implicit assumption that equality means one of the things that LISP offers but if you want the other definitions of equality you either have to build support for them by hand or call out to a library function that's going to use (static or dynamic) reflection to reduce the problem to the one kind of equality the language implements.
(Apart from that, the only other complaint is that LISP being as old as it is, the default names for those equalities are too terse to self-describe. You just have to memorize which one is 'eq' and which one is 'eql', there's no way to guess looking at the names themselves).
https://www.reddit.com/r/ProgrammerHumor/comments/225i15/pro...
(To contextualize and clarify: It's a classic old JavaScript joke about how Brendan Eich hates gay people getting married so much that he donated money to a political campaign against marriage equality, even though he enjoys the human right of marriage himself. Some bigots think they are more equal than others.)
- std::nullopt_t
- std::nullptr_t
- std::monostate
- std::tuple<>
And I'm sure there's more.
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.
Using one type to represent empty literals for optional, tuple and pointer types, implicitly convertible to all of them, would make the compiler accept many obviously accidental constructs. In a world where the maintainers of C++ are trying their hardest to make the language safer what conceivable benefit would there be?
A function returning bottom cannot return, yet void foo() {} can. In fact it can even return the result of calling other void functions:
void bar() { }
void foo(){ return bar();}
In generic code void is usually internally replaced by a proper, regular void_t unit type and converted back to void at boundaries for backward compatibility. [[noreturn]] void bar();
would be a candidate for a bottom-returning function, except that [[noreturn]] isn't really part of the type system.C and C++ don't have a type spindle, where void would be at the bottom. Only C++ has the concept of subtype, only in the class system, and the C++ class system doesn't have a bottom type; there is no bottom class that is a base for all the others.
void is not a proper type; it's just a hack shoehorned into a convenient spot in the type system.
Which is why the C++ people have to invent this whole zoo of other things.
If void were a type, then, for starters, "return x;" would be syntactically valid in a function returning void. (Only, no possible x would satisfy the type system, so there would have to be a diagnosable rule violation in that regard.)
A function returning void does not return a type. It doesn't return anything; it is a procedure invoked for side effects.
The same situation could be achieved in other ways, like having a procedure keyword instead of void.
The (void) parameter list is another example of void just being a hack. It was introduced in ISO C, and then C++ adopted it for compatibility.
The 2023 draft of ISO C finally made () equivalent to (void), though it will probably take many decades for (void) to disappear.
The word/type they wanted for this was the Unit type: https://en.wikipedia.org/wiki/Unit_type and in that list it even states the `std:monotype` is a Unit.
Like, if we assume someone looking at code with `std::unit`, what might they think this is? If one is not aware of its use in ML or similar, it could just as easily be assumed that it could be something to do with units like meters or kilograms or whatnot. After all, the C++ standard library is vast so it wouldn't necessarily be all that far-fetched.
Then the only question would be to ask why it would be default-constructible. At which point you'd have to read the docs for the type anyway.
And if my grandmother had wheels she'd be a bicycle. Of course if there wasn't a standard name for this concept that had been used in the industry for 50+ years (and in theoretical work for over 100) then it wouldn't make any difference what name you used for it. But given that there is a standard name for this concept that has been used in the industry for 50+ years, making up a different name is pretty unfortunate.
But to their dismay the crazier it gets, the more some people dig in and embrace it even more.
/sarcasm. I think.
The C++ usage was introduced by Jim Coplien in his 1992 book as a succinct name for an architectural pattern in C++: https://archive.org/details/advancedcbsprogr00copl/page/166/...
It's common enough that articles have been written against this usage: https://web.archive.org/web/20170224220253/http://jackieokay...
So this usage of functor may never have been "official", but it's widespread in the community.
The word "functor" has a long and glorious history in C++. Try entering "C++ Andrei Alexandrescu functors" into your internet search engine of choice. For bonus points, try "c++ Scott Meyers functor" as well.
https://stackoverflow.com/questions/54336641/is-there-any-re...
Before C++ popularized the term, other programming languages and libraries had already used "vector" to describe similar data structures. For example, Common Lisp has a vector type that represents a one-dimensional array.
Interview with him acknowledging this:
And computing has interrupt vectors as well.
In ML and friends monostate is called unit (and gets used a lot because void returns aren't allowed by the languages). Some have empty types too, which can never be occupied. A function returning Empty can't return, for example, though there are other use cases
But here we are talking about C++, where "void" is a pseudotype that is absolutely inhabited, in some conceptual sense. Any function that is declared to return void and which returns is returning a thing that conceptually inhabits void. In this sense, std::monostate indeed captures the same concept as void, but in a much better way, because it's properly a type, not a pseudotype.
Note: Java does the same thing, effectively, with "Void" which is inhabited by exactly one value: null.
I'd accept that it's not the same as the empty type though, given that void* can be occupied and functions marked void can return. Probably someone with more type theory than me can name this properly
> a fancy way to say void?
Less fancy and more workable. Had void been a proper type in the first place it would not have been needed (but also… void had the same issue as nothing, it sounds like an uninhabited type more than a unit type).
Despite that, they could have called it Void, even if the standard library normally uses all lowercase.
Void doesn’t exist in ML
—- Haskell
data Void
(* Standard ML *)
datatype void = Void of voidIn category theory terms, I believe void is the initial type (there is exactly one morphism from void to any other type), whereas monostate is the terminal type (there is exactly one morphism from any other type to monotype).
template<typename T = std::monostate>
class C
{
...
if constexpr (!std::is_same_v<T, std::monostate>
{
// T-related behaviour here
}
};Anyway, I write basically this on my blog for a more thorough explanation: https://www.jackyoustra.com/blog/non-equatable-void
Hans: No -- it does nothing.
This thing is just a counterpart to void that is a class. A better name would be voidclass or something along those lines.
(There is a Monostate pattern, but that involves a class with state: just all the state is static. It's basically like a module with global variables. Completely different thing.)
But in a way, this is right since:
<no of bits>
2 = <no of states>
When the number of bits is 0, 2^0 = 1: 1 state. A state machine with one state is certainly possible.Problem is we need 2 or more states to do anything useful with state. We can draw an initial state bubble in a state diagram and not add any states; it can even have transitions back to itself.
So maybe monostate is not exactly a misnomer; it's just weird to mention state about something that is not useful for working with state.
Not everything can or should be default-constructed or default-constructible. That does complicate initialization sometimes (i.e. there are practical reasons to "suspend" construction until you have all the needed data), but you're not avoiding breaking type safety by adding a `monostate`, you're just giving yourself the "could be null" headache.
In my mind, a computation (a “function”) must either return a value or hang/crash. If it appears as though it returns a member of ∅, it must hang/crash, because there are no members of ∅. If it returns a member of the single-element set, [1], it can return one, there’s just no use inspecting it afterwards (you know what it is already).
(For what it’s worth, if you use a prover-adjacent language such as Agda or Idris, this is exactly how things are going to work there.)
std::variant<int, whatever> v;
// v is zero
and std::variant<int, whatever> v = 0;
And don't want to pay the space and time overhead of wrapping in an std::optional which will use a whole other byte at least for not good reasonThe size of an optional<T> is `sizeof T + 1` because it needs a boolean for the set/unset flag.
The size of a variant is… the same, at least, because it needs to store a discriminator integer (apparently both gcc and clang do optimise to a byte when there are less than 256 variants).
Or do you mean adding a monostate to an existing variant rather than wrap that variant into an `optional`? In which case you should fix your example (and provide a version wrapped in an optional) because they’re very confusing.
Current situation: you have
std::variant<int, whatever> x;
you now want to discriminate on whenever x has been initialized explicitly or not, the two cases I posted: // case 1
std::variant<int, whatever> x;
// case 2
std::variant<int, whatever> x = 0;
you have two options:option A: does not needlessly increase sizeof, does not add indirection penalty upon access:
std::variant<std::monostate, int, whatever> x;
option B: needlessly increases sizeof, adds indirection penalty upon access (mostly relevant when compiling in debug mode without inlining if you still want to have a semblance of performance): std::optional<std::variant<int, whatever>> x;Brevity, I guess? I suppose the most brief way to express absence or presence of value in C++ is a pointer, but I could be tried at the Hague for that take.
None of this is to be facetious, I'm really trying to learn here. I'm not a C++ guy by trade. C and Rust are my day-to-day languages.
std::variant<std::monostate, T, U, V>
Or std::optional<std::variant<T, U, V>>
But then the "none" state is a bit more "special", it's not just one of the options. The sizeof of the type will also probably be a bit bigger, because it has to contain both the bool for the optional, as well as the tag for the variant.The other obvious use is what the article states, that it allows the variant to be default constructed even if none of its members are. Though you can do that with optional as well. It's mostly a matter of style. I mostly avoid std::monostate because the name is so confusing, I really agree with the other users that something like std::unit or std::none would be better.
This. monostate's behavior should be captured in the std::optional spec. There's no need to create a new type.