Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does C++ not allow user-defined operators?

I've been wondering this for quite some time. There are already a whole bunch of them and they can be overloaded, so why not do it to the end and allow custom operators? I think it could be a great addition.

I've been told that this would make the language too hard to compile. This makes me wonder, C++ cannot really be designed for easy compilation anyway, so is it really undoable? Of course, if you use an LR parser with a static table and a grammar such as

E → T + E | T
T → F * T | F
F → id | '(' E ')'

it wouldn't work. In Prolog, which is usually parsed with a Operator-Precedence parser AFAIK, new operators can easily be defined, but the language is much simpler. Now, the grammar could obviously be rewritten to accept identifiers in every place where an operator is hard-coded into the grammar.

What other solutions and parser schemes are there and what other things have influenced that design decision?

like image 212
Felix Dombek Avatar asked Dec 13 '22 17:12

Felix Dombek


1 Answers

http://www2.research.att.com/~bs/bs_faq2.html#overload-operator

The possibility has been considered several times, but each time I/we decided that the likely problems outweighed the likely benefits.

It's not a language-technical problem. Even when I first considerd it in 1983, I knew how it could be implemented. However, my experience has been that when we go beyond the most trivial examples people seem to have subtlely different opinions of "the obvious" meaning of uses of an operator. A classical example is a**b**c. Assume that ** has been made to mean exponentiation. Now should a**b**c mean (a**b)**c or a**(b**c)? I thought the answer was obvious and my friends agreed - and then we found that we didn't agree on which resolution was the obvious one. My conjecture is that such problems would lead to subtle bugs.

like image 153
mvladic Avatar answered Jan 01 '23 14:01

mvladic