Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Operator Precedence Overloading in C++

Tags:

Why can you not change the operator precedence when you overload operators in C++? For example, if you had a class in which it would make sense to do addition before multiplication, how could you make the addition operator have higher precedence than the multiplication one?

This is different from this question Operator overloading and precedence because I am asking why, and how to work around this restriction.

I would prefer to avoid compiler customization, and use only C++14 standards. Third-party libraries are OK.

like image 258
パスカル Avatar asked Mar 07 '17 15:03

パスカル


1 Answers

Traditional compiler design parses the grammar first, before figuring out where each operator comes from.

Compiler design tools like YACC existed long before C++. As such, traditional compilers evolved over time following the general principle of parsing the syntax of the source code first, then trying to figure out what to do with each operator. So, the compiler sees the structure of the language first, and foremost; and the C++ standard actually wants to make it possible to write a C++ compiler without reinventing every wheel that has been invented, already.

like image 157
Sam Varshavchik Avatar answered Sep 24 '22 10:09

Sam Varshavchik