12 ms·
Comparisons in C++20
- voldacar 7y agoA new string type! How exciting!
- 2bitencryption 7y agothe article doesn't describe a new string type anywhere, only a hypothetical one for the purposes of demonstrating the new operator
- metiscus 7y agoI didn't see anything about a new string type. This does greatly simplify writing comparison operators and makes the compiler smarter about != Is actually a composition of ! (==). The spaceship operator is going to be a huge change.
- mehrdadn 7y agoThe terminology is a little confusing. By "strong" total ordering do they really mean "strict" total ordering? If not, what's the difference?
- giomasce 7y agoNo. The terminology is different because it refers to a different concept. In C++20 "strong" vs "weak" refers to substitutability. When two elements x and y compare to strong_ordering::equal, then it is assumed that f(x) == f(y). This is not assumed if they are just weak_ordering::equivalent. Read section "A new ordering primitive: <=>" of the article for a longer explanation.
- mehrdadn 7y agoI did read that section... that's why I said it's confusing... It seems to me they're using different terminology for concepts that aren't different in math? In math, "equality" (=) already means the same thing as substitutability. A non-substitutable equality is already called "equivalence" (≡). So in math we already have these: [1a] Non-strict partial order: a binary ordering that allows incomparability (≼, ≡, ≽, ?) [1b] Strict partial order: like [1a], but irreflexive (≺, ≡, ≻, ?) [2a] Non-strict weak order: like [1a], but with all elements comparable (≼, ≡, ≽) [2b] Strict weak order: like [1b], but with all elements comparable (≺, ≡, ≻) [3a] Non-strict total order: like [2a], where the equivalence is equality (≤, =, ≥) [3b] Strict total order: like [2b], where the equivalence is equality (<, =, >) If I didn't make a mistake above, then: - C++'s "strong total ordering" seems to be what in math we call "strict total ordering" - Their "weak total ordering" seems to be what in math we call "strict weak ordering" - Partial order is the same thing for both Am I wrong here? If yes, how? If not, why did they randomly invent their own terminology? I haven't seen their definitions used elsewhere.
- giomasce 7y agoDo not try too hard to compare with maths here. A programming language is different in many things from how maths is usually formalized. In C++20 there is no "strong total ordering", "weak total ordering" nor their partial counterparts. There are just "strong ordering", "weak ordering" and "partial ordering". In a strong ordering, two objects can only by one smaller, equal or larger than the other. If they are equal, it means that they are substitutable. In a weak ordering, two objects can only be one smaller, equivalent or larger than the other. No substitutability is implied. In a partial ordering, two objects can be one smaller, equivalent or larger than the other, or just not comparable. Again, no substitutability is implied. There is no point in distinguishing strict vs non-strict: depending on whether you call < or <= you will get the string or not string variant, and the same for > and >=.
- Sniffnoy 7y agoHuh, this is... not the terminology I am used to, as a mathematician? My experience is that what C++ is calling a "weak order", and what you are calling a "weak order", is what in math is called a "pre-order" or a "quasi-order". Meanwhile, the distinction you are making between strict and nonstrict is just ignored (except by constructivists), since they're equivalent ways of talking about the same thing. Indeed I'm not sure why you included both because, well, they're just two ways of talking about the same thing (again, unless you're a constructivist). Really (assuming classical logic) there's just 4 possibilities here: 1. Total order (what they're calling a "strong ordering") 2. Total preorder (what they're calling a "weak ordering") 3. Partial order (which they are also calling a "partial ordering") 4. Partial preorder (which they don't account for)
- mehrdadn 7y agoYou're agreeing with me? "Preorder" is just a (better-known?) synonym for "non-strict weak order" [1] [2], so we don't disagree there. "Strict" vs. "non-strict" I merely included because C++ comparisons return strict orders. I thought it was worth including, but feel free to ignore it. So just as you pointed out in your own list, and just as I've been saying, "strong total order" isn't the terminology (every total order is strong), and neither is "weak total order" (it means "total preorder" which is... just a total order). Like you said, they should say "total" order, "preorder" (or "weak" order as I said), "partial" order. The "strong" and "weak total" stuff is just something they seem to have invented in contradiction with the established mathematical terminology for... no reason/gain? [1] https://en.wikipedia.org/wiki/Weak_ordering#Total_preorders https://en.wikipedia.org/wiki/Weak_ordering#Total_preorders [2] http://fitelson.org/roberts_measurement_theory.pdf#page=56 http://fitelson.org/roberts_measurement_theory.pdf#page=56
- wyldfire 7y agoAn early c++20 fan gives a tribute to his favorite new operator [1] (indeed so early it was only drafts back then). [1] https://youtu.be/ZA6ehndc6co https://youtu.be/ZA6ehndc6co
- twoodfin 7y agoHow do the literal 0 comparisons fit into the language? Are they special purpose syntax or is it possible to write your own operator that only typechecks if the RHS is a literal 0?
- wyldfire 7y agoAre you confusing the implementation of these operator overloads with their signature? The spaceship returns {neg, 0, pos} and that's why the implementations are like that.
- twoodfin 7y agoI’m referring to this bit of the article: The values of these comparison categories can be compared against the literal 0 (not any int, not an int whose value is 0... just the literal) using any of the six comparison operators...
- wyldfire 7y agoOh, this is particularly confusing, I agree. IIUC it's referring to how you can safely evaluate the return value from a spaceship: by comparing against literal zero. (not how you would overload a comparison with literal zero).
- yokohummer7 7y agoC and C++ already have such a thing, IIUC. The literal 0 is considered the same as nullptr, if compared to another pointer. It is a bit worrying that such an overloaded meaning is added again to the language.
- Demiurge 7y agoThis is interesting... As non-C++ developer, I've never thought I needed this. Is this an answer to a question anyone is asking?
- wyldfire 7y agoYes, your favorite high level language might provide something like this implicitly.
- maxlybbert 7y agoPerl has had this for decades. C’s strcmp() has similar semantics. I thought the motivation was that sort can be more efficient when each comparison can return more information (the standard library already has a sort function that relies only on using less-than operations). But people eventually realized that certain operations have to be implemented together to make sense. For instance, the sort function that relies only on less-than operations defines two values as equal if neither value is less than the other. Many people consider this weird, and wonder why sort doesn’t require both less-than and equality operations. The spaceship operator essentially implements a group of operations, and guarantees they’ll be consistent: less-than, equal, and greater-than (plus not-equal, less-than-or-equal, and greater-than-or-equal). Personally, I’m not thrilled about a special purpose solution to a single example of a problem (use this one operator to implement this group of related operations), but I do see some value in making it easy to implement this group of related operations.
- ksherlock 7y agoYes. Aside from reducing repetitive code (replacing 7 overloaded comparison operators) it's probably more efficient. std::map, for example, currently uses a less-than comparator to order items, requiring multiple comparisons to check if items are equal.
- mehrdadn 7y agoThe part you probably needed is 3-way comparisons. The weak vs. strong vs. distinction is less likely to be needed IMO.
- de_watcher 7y ago
- inlined 7y agoThe default operators are very cool, but I assume that many codebases would ban them. Imagine, for example, an engineer decided to reorder members in a struct to make it pack better. Now the semantics of default <=> have changed! Also, as a minor nit, the optional number sample has a possible bug. I would assume that two null optionals would compare equivalently. Or is that part of how <=> should work? Should NaN <=> NaN == partial_ordering::unordered?
- maxwellburson 7y agoWhile I don't know about this specific case, I do know in some languages, like JavaScript, NaN poisons any operation it is part of. So any operation on it is NaN, and comparisons to it are false.
- magicalhippo 7y agoThis is default IEEE 754 behavior. https://en.wikipedia.org/wiki/NaN https://en.wikipedia.org/wiki/NaN
- yablak 7y agoYes, the standard and expected behavior is that logical_op(NaN, anything) == false [except inequality] because NaN is not ordered with, or equal to, anything, including another NaN. Otherwise you may have the strange behavior that two erroneous values are equal, e.g., 0*inf == tan(inf).
- jcranmer 7y agoI don't have the IEEE 754 specification in front of me to verify, but the usual descriptions of floating point comparison considers it to be a 4-value (<, =, >, unordered), with 16 different operators defining for which of those values the comparison returns true. So an ordered equals returns true only when the result is =, but an unordered equals returns true if the result is = or unordered. The unordered operation is returned if either operand is unordered, which makes the comparison non-reflexive. Note that floating point is already weird, because most languages make == reflect the ordered equals, not the unordered equals, and so the primitive equality for floats violates the reflexive principle (i.e., x == x returns false).
- giomasce 7y agoIn case someone rushed to cppreference.com to compare, I think that https://en.cppreference.com/w/cpp/utility/compare/strong_ordering https://en.cppreference.com/w/cpp/utility/compare/strong_ord... is slightly wrong, in that it should not list "equivalent" as an alternative. I reported that (putative) mistake.
- notmuchserious 7y agoA brand new language without backward compatibility would be nice. C+++
- wyldfire 7y agoRust and D are pretty close to just that IMO. BTW the new language standards do make backwards incompatible changes. C++17, for example, deletes several features which were deprecated. And [1] is an egregious example. [1] https://stackoverflow.com/a/620402/489590 https://stackoverflow.com/a/620402/489590
- ThePadawan 7y agoJust in case you didn't know, the "adding +" part of your idea is what inspired the naming of C#. If you look at the #, it is supposed to represent two columns of two + each.
- de_watcher 7y agoThe whole point is to have backwards compatibility. It's just fascinating how they add or fix things without breaking the code. Doing without backwards compatibility is easy: take Rust or D.
- Crinus 7y ago> It's just fascinating how they add or fix things without breaking the code. In the same way it is fascinating to watch a forest fire from afar.
- ohazi 7y ago> Importantly, there is no language transformation which rewrites one kind of operator (i.e. Equality or Ordering) in terms of a different kind of operator. The columns are strictly separate. Why do we need a primary == operator if we have strong_ordering::equal, weak_ordering::equivalent, and partial_ordering::equivalent? Couldn't the behavior of == and != be inferred from the <=> definition? I guess I'm asking why a == b can't be rewritten as (a <=> b) == 0.
- cornstalks 7y agoSome types might implement == but not <=>. For these types, == needs to be a primary operator. But for types that implement <=>, I'm not sure why == isn't automagically generated.
- tsimionescu 7y agoThere is an explanation in the article - basically, this is done for performance reasons. Especially for large types (e.g. collections) in-equality can short-circuit very quickly, whereas comparison may need to see a large part of the collection before being able to return. The most pathological example is two large arrays of different size, that are element-by-element equal for the first million elements. Equality can return false after seeing the size difference, but <=> needs to reach the millionth-and-1 element before being bale to return a value. The commission was especially concerned because the two operators would be functionally equivalent - so, it would be difficult to rely on testing to make sure the equality operator is also implemented.
- username90 7y ago> Why do we need a primary == operator if we have strong_ordering::equal, weak_ordering::equivalent Weak orderings are defined as orders that can't distinguish between all members, which is why it is called "equivalent" instead of "equal".
- ohazi 7y ago> Weak orderings are defined as orders that can't distinguish between all members I get that. This wasn't my question. I want to know why I need to define operator== when reasonable behavior can be inferred from whether or not operator<=> returns strong_ordering::equal (or weak_ordering::equivalent -- the standards committee can decide if this is reasonable -- I don't really care). If I want special behavior, then sure, defining operator== might make sense, and then it should obviously take precedence. But if the whole point of this new three way compare is to reduce the combinatorial explosion of things that you need to define, I don't understand the need to split the universe into {==, !=} and {<=>, <, <=, >, >=}, and never let them interact with each other. The part I take issue with is the statement "The columns are strictly separate." Maybe I've missed something, but I don't see why it needs to be like this. operator<=> seems to be a strict superset of operator==, because it returns information about when equality holds, (or when equivalence holds). Shouldn't that be sufficient? Also, what's going to break if you design a type where a.operator==(b) doesn't return true when a.operator<=>(b) returns strong_ordering::equal, or vice-versa? Again, maybe I've missed something, but this seems like a mistake. They're removing all of the footguns except this last one. Why?
- forrestthewoods 7y agoGod this is so confusing. Why the $%&* does it take a 17-page 27-minute blog post to explain how to implement comparison operators? Can someone please write the 3-minute blog post that is easy to understand and follow? If the answer is "it's too complicated to explain in 3 minutes" then I think that is a telling sign.
- gumby 7y agoHere you go: less than 3 minutes to type out! "The TL;DR is that there's a new operator, <=>, that returns less than 0, 0, or greater than zero, just like, say, strcmp does, but for all sorts of C++ objects. You can define operator<=> and operator== and your compiler will take care of the various other comparators. Doing this speeds up some library functions, doesn't force you to write as much code, and makes comparisons more intuitive. "There are also a bunch of corner case optimizations but if you don't care about them you don't need to know" This was written by someone who cares about the corner cases and underlying theory. It's like FP: IEEE743 is full of weirdo cases that some really smart people spent a lot of time worrying about. All most users care about is that "they have a fractional representation and that == doesn't reliably work except against 0.0." Just because there's hundreds of pages in that spec doesn't make it dumb either.
- furyofantares 7y agoI don't think this is right. In order to implement <=> for a class, you have to understand strong_ordering, weak_ordering, and partial_ordering in order to pick one, right?
- slavik81 7y agoGenerally, no. Most of the time you're going to write these functions as defaulted with an auto return type: auto operator<=>(const T&) const = default; bool operator==(const T&) const = default; The compiler will implement the function by comparing all the class member variables and will pick the type of the ordering as appropriate. You only need to look into further details about ordering types if you want to do something fancy.
- makecheck 7y agoOne of the most frustrating bugs I encountered in a previous job was an incorrect implementation of a “strict weak ordering” that would cause containers and algorithms to just plain misbehave. The evil part was that there was a whole range of misbehavior, including “generally working” for most data, while crashing in other cases! The reality is that most programmers are not experts but they exist on C++ projects. People will try “simple” things like hacking up a less-than operator, and when it seems to “work”, they move on (leaving a code time bomb behind). The C++ compiler needs to provide robust compile-time and run-time checks to tell programmers that things are wrong, like: “your operator does not meet the requirements of the sort algorithm”. Contrast the latest 20-page description of std::whatever_the_heck to, say, Python sorting, which offers "key=..." because the overwhelmingly common case is to simply state a single field on which to base object ordering!!!
- mort96 7y agoI'm working on a game. I have a templated 2D vector implementation. Tile positions use Vector2<int>, entity positions and such use Vector2<float>. I wanted a map from tile position to something else. I found that I had to implement operator<, because std::map uses operator<. That's an issue, because: 1. I didn't want to implement every single possible comparison operator just to put vectors in an array, but also didn't want to arbitrarily make `foo < bar` legal but `foo > bar` illegal. 2. What does it even mean for one vector to be "bigger than" another vector? For vector math purposes, I'd maybe expect operator< to compare magnitudes, but that would be absolutely terrible for std::map. Not everything has an unambiguous concept of "smaller than". In the end I just made a std::map<std::pair<int, int>> and added an implicit conversion from Vector2<T> to std::pair<T, T>.
- iso-8859-1 7y agoIt's funny how Concepts are not mentioned at all. Given that they are the C++ equivalent of type classes and a common example is the "EqualityConstraint", I can't believe there isn't some interplay. Concepts are also in C++20.
- debatem1 7y agoI've thought for years that C++ was a sprawling mess of a language with a good and useful subset buried in there somewhere. I'm giving up with C++20. It's time to acknowledge that the language is too big and its virtues too small.
- carlsborg 7y agoAgree, the direction this is going is outdated. Complexity is expensive and erstwhile c++ programmers are now in in cto positions or are responsible for budgets and know this. The c++ standards need to focus on adding to developer productivity by incorporating micropython to make it more accessible.
- gpderetta 7y agoSure, the language is not complex enough, let's bolt another language on top of it. The spaceship operator is exactly an attempt to make the language more accessible, but of course is being dismissed here as anything c++.
- carlsborg 7y agoMaybe it’s useful and I appreciate the effort going into this. But consider you have a legacy c++ system in a large bank. The argument “we can extend this with a subset of python” can win over “when do we rewrite this in java or nodejs” which are the real conversations that have been taking place over the last decade.
- deleted 7y ago[deleted]
- skgoa 7y agoIt seems to be a matter of propper balance. You can elevate patterns, idioms etc. to language features and you can add entirely new features that enable entirely new solutions. Java and Python are doing this sensibly. But burying devs in an avalanche of new language features that change the way you are supposed to do fundamental things is going to make it much harder to keep up. Especially when this happens every 3 years.
- moomin 7y agoInteresting to compare to Haskell. Here you typically implement “compare” which is equivalent to the spaceship operator and get < &c for free, but you can implement “<=“ and get compare for free because the defaulting mechanism is general and not built into the compiler. Also “Ord” has to be compatible with “Eq” (which you can also get for free) which is different from C++’s approach. Moreover, the compiler can “derive” implementations for regular data objects. C# is slightly different: all of the algorithms take an IComparison, which implements the spaceship operator in another class (you can implement the related IComparer in your actual class and it all works via the magic of reflection. This isn't too bad since the reflection only occurs in the constructor.). Comparison operators are basically never used in the standard library and people rarely implement them.
- claudius 7y ago> Moreover, the compiler can “derive” implementations for regular data objects. When defaulting the spaceship operator, the same happens for C++ (by comparing members). In this special case, the equality operator is also effectively defaulted, so as described in the article struct A { … auto operator<=>(A const& rhs) const = default; }; gives you automatic member-wise comparison "derived" by the compiler.
- moomin 7y agoNice, I missed that.
- kensai 7y agoI really hope a modern language can take over many features of C++ without its added complexity. Potential candidates: Rust, Julia, Swift. All three are modern languages with modern concepts. I have high hopes especially for Julia.
- nevi-me 7y agoPlease excuse my lack of knowledge, but is Julia gen-purp enough to replace C++? Can I write a hypothetical kernel with it, or a game?
- cshenton 7y agoGame? Sure, if you’re willing to spend a non trivial amount of time integrating with a graphics API, but that’s true of most non C++ languages. Kernel? Probably not, AFAIK there’s no subset of Julia that can run without an OS (like for rust and C++).
- psychoslave 7y agoTo me it seems obvious that you can write any application using any Turin-complete language. So the question seems more like "how convenient would it be to write a kernel or a game using Julia and with which performance impact?" For games, it will highly depends what kind of game, of course. Assuming cutting-edge 3d-graphic intensive video-game, it will be probably not be your language of choice, especially regarding available out of the box libraries. For implementing Tetris, I guess you make it in any language for sufficient performance. :)
- pjmlp 7y agoSwift is only a candidate in the context of Apple OSes, and yes Apple does position it as such on the Swift documentation. Outside Apple platforms, maybe Rust, but it still found lacking in tooling and libraries versus what C++ offers, specially in graphics programming, GPGPU, embedded platforms, and IDEs. Maybe now that Microsoft is looking into it, we might get Visual Rust of some sort. Julia is more a replacement for Python than anything else. Then if having a GC around is not a problem for the task being solved, there are plenty of alternatives out there, Java, C#, F#, OCaml, Haskell, Lisp, Scheme, ....