-
Notifications
You must be signed in to change notification settings - Fork 251
Design note: Postfix unary operators vs binary operators
Herb Sutter edited this page Oct 10, 2022
·
7 revisions
There is a tension between two things:
- most unary operators including
*
and&
naturally want to be postfix (*), and - we want to support all Cpp1 operators in order to ensure great compatibility with all existing C++ libraries including those that overload all the possible operators (e.g., expression templates) but that includes binary
*
and&
So if we want to have both, we have a few choices, including:
- Change the syntax of pointers/dereference to use something that is not a binary operator. For example, a lot of people would suggest one of the very few unused symbols, notably
@
. But note that we only ever get to take each one of those once, ever, in all the history of time, so we should have a truly break-the-glass no-other-option reason to take it. This doesn't rise to that bar. - Change the syntax of pointers/dereference to use another operator that has a binary form we can ban. Here the notable and obvious example is
^
, and in Cpp2 for a while I actually used^
for pointers/deference and banned the bitwise binary operators and required programmers to writebitxor
et al. instead, which is arguably more readable (and the slightly longer spelling highlights an important operation, and they're already alternative tokens, and there are alreadystd::
versions, and other rationale/rationalizations). But the moment I tried converting spdlog to Cpp2 syntax by hand a year ago, I found myself having to convert a lot of those, and after the first dozen I realized that banning the bitwise binary operators was a nontrivial impediment to the more important goal of making converting code to Cpp2 as friction-free as possible. - Disambiguate unary and binary
*
and&
. This is what I'm currently trying... the current rule is that the suffix unary operators must have no whitespace (which I think is natural, and nobody seems to have noticed this yet and reported it so it seems nobody has tried to writeiter ++
which seems to be early validation this choice is acceptable) and*
and&
that appear as a suffix are the unary operators unless they are the last operator and are followed by(
or an identifier (or, now, a literal, thanks for pointing this out) which wouldn't be legal anyway for a unary operator. This is an experiment but so far it's working well for my uses.
(*) for now please grant this for the sake of discussion... briefly, this follows from declaration syntax mirroring use syntax and as I promised in the talk, I'll write it up soon as another Design Note here