-
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 Mar 23, 2024
·
7 revisions
There is a tension between two things:
- most unary operators including
*
and&
naturally want to be postfix (see Design note: Postfix operators), 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 if can be a postfix operator, it is. For example,a*b
anda&b
must be binary operators because they are followed by an identifier, it would be grammatically invalid for them to be postfix operators in those examples.