Reputation: 1521
In C++ I can define an alias to existing type via typedef
statement.
But can one create an alias to an operator?
To be specific, I want to pick some Unicode symbol and create an alias to <<
operator.
I would like to use for example "Vertical Four Dots" U+205E
:
cout
⁞ endl ⁞ "filename: " ⁞ cfgfilename
⁞ endl ⁞ "message: " ⁞ e.what()
⁞ endl ⁞ "exception id: " ⁞ e.id
⁞ endl ⁞ "byte position: " ⁞ e.byte ;
Instead of this:
cout
<< endl << "filename: " << cfgfilename
<< endl << "message: " << e.what()
<< endl << "exception id: " << e.id
<< endl << "byte position: " << e.byte ;
If it is not possible with the Four Dots character, but some other symbols, it could be an option as well (though it would be good to have more options than basic ASCII).
Upvotes: 0
Views: 1122
Reputation: 4169
C++ only allows operators to be overloaded, not newly defined. So you can re-define what <<
does, but you can't define a new operator like ⁞
.
It has certainly been considered over the evolution of the language, and Bjarne Stroustrup himself (the guy who wrote C++) has explained why they decided not to allow it:
Can I define my own operators?
Sorry, no. 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.
Best you can probably do is add a build step that replaces ⁞
with <<
before passing the compilation unit to the compiler. Depending on your build environment, this is probably fairly straightforward with a make
file or equivalent.
Acknowledgement: I got a lot of inspiration from this answer.
Upvotes: 6
Reputation: 141060
There is a list of available operators that are available for operator overloading. So you can't create an operator for your custom character to be your custom character overloaded operator.
Aside from that, C++ standard defines the character set which can be used to write programs. The unicode characters are not valid inside a C++ source file as the name for an operator overload.
Upvotes: 1