Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can spaceship operator be used in fold expressions?

None of the compilers I tried accept such code:

template <int ...a> bool foo() { return (a<=> ... <=>0); }

But for any other <=,>=,==,!=,<,> it compiles.

cppreference is clear here - there is no <=> on the list of binary operators we can use for fold expression.

Is this an intentional omission in the C++ standard, or are compilers not ready with this?

The question is just pure curiosity; I just wanted to know what the C++ direction is in this area. I can imagine all other compare operators will be removed from the fold-expression list of allowed operators, as they have as much sense as <=> in a fold expression...

like image 838
PiotrNycz Avatar asked Aug 06 '21 14:08

PiotrNycz


People also ask

What is the point of the spaceship operator?

In PHP 7, a new feature, spaceship operator has been introduced. It is used to compare two expressions. It returns -1, 0 or 1 when first expression is respectively less than, equal to, or greater than second expression.

What is the spaceship operator C++?

In C++, the C++20 revision adds the "spaceship operator" <=> , which similarly returns the sign of the difference and can also return different types (convertible to signed integers) depending on the strictness of the comparison.

What is fold expression?

A fold expression is an instruction for the compiler to repeat the application of an operator over a variadic template pack. Let's take an example. A very basic one and with a questionable usefulness, but one that illustrates how fold expressions work.

What is three-way comparison operator C++?

The C++20 three-way comparison operator <=> (commonly nicknamed the spaceship operator due to its appearance) compares two items and describes the result. It's called the three-way comparison because there are five possible results: less, equal, equivalent, greater, and unordered.


1 Answers

This is intentional.

The problem with fold-expanding comparison operators is that it works by doing this: A < B < C < D. This is only meaningfully useful in circumstances where operator< has been overloaded to mean something other than comparison. This is why an attempt was made to stop C++17 from allowing you to fold over them in the first place.

operator<=> is never supposed to be used for something other than comparison. So it is forbidden.

like image 106
Nicol Bolas Avatar answered Oct 16 '22 05:10

Nicol Bolas