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

> I'm not sure I grok the `<=>` operator

Think of `strcmp` which returns an int. The int can be <0, ==0, or >0. That same `strcmp` can then be used to implement all other standard comparison functions. `operator <=>` is the generalized version of that.



An important part there is: Most users will never call <=> themselves. However somebody implementing a type can implement a single function and the compiler will translate usage of <, <=, ==, !=< >=, > to the single function. Reduces boiler plate in the implementation. (Think about it - most implementations of > or < will often use the same logic already, spelling this out is "annoying"; mind that for performance reasons it can still be worthwhile to implement a == explicitly as equal comparison is often faster than ordering, but that's something the type designer can chose)


> Think about it - most implementations of > or < will often use the same logic already, spelling this out is "annoying"; mind that for performance reasons it can still be worthwhile to implement a == explicitly as equal comparison is often faster than ordering, but that's something the type designer can chose

Yup. My C++ code would often include a `int T.compare(const T& a)` member function. Then any comparison operator would be custom written too -- but only to delegate to the custom compare and check its result.

This one feature alone will eliminate several lines of boilerplate.


Do you have an example of when == would be faster than a comparison?

I can't think of any case that would have any appreciable difference in speed.

Is it mostly around eliminating branching logic?

Wouldn't there be a good chance that might be inlined and optimized away anyways?


On case is string comparison. When implementing == I can shortcut if length doesn't matter the string can't be equal. When implementing <=> I however have to iterate in any case. (While there the question then is if the shortcut is really efficient, as the iteration might already stop on first character ...)




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

Search: