About: Hi, I'm Swastik Baranwal, a software developer from New Delhi, India passionate about open-source contribution, Gopher, Pythoneer, Compiler Design and DevOps.
Location:
Delhi, India
Joined:
Oct 7, 2019
C++ Named Operators
Publish Date: Jun 1 '20
13 0
As I was revising C++ again because I am not using it daily but today what I have discovered is something that many people and even Fluent C++ Programmers don't know about. I am about to introduce Named Operators.
This post uses klmr/named-operator library because it is convenient to explain and to look at.
Named Operators
Named Operators are those operators which are custom named and are surrounded by symbols like +, -, * etc. It is similar to how Haskell does it.
std::vector<int>={1,2,24};boolresult=24<in>vec;
Definition
Operators can be defined for any function-like object by calling make_named_operator:
autodiv=make_named_operator(div);
where
intdiv(intx,inty){return{x/y};}
Or, if you prefer functors (and yes, templates work just fine):
Overloading operators with unconventional semantics generally frowned upon because it violates the user’s expectations (although it has variously been used to great effect).
Furthermore, the set of operators that can be created in this fashion is limited to a subset of the built-in operators.
On the other hand, using infix notation instead of function calls can undeniably make code more readable, especially when nesting lots of operations. Compare
Other languages have recognized and addressed this problem.
Since C++ allows overloading operators for custom types, named operators can be implemented by simply sticking a place-holder object between two overloaded operators (which can be entirely arbitrary):
These declarations are enough to make the following syntax valid:
intx,y,z;z=x<op>y;
Of course, what the compiler really sees is
z=operator>(operator<(x,op),y);
This already highlights a problem: operator precedence. In effect, op will have the precedence of its surrounding operators. In particular, the precedence of < and > is very low