Can I create a new operator in C++ and how?
Solution 1:
No, you can't overload op.*
:
[C++03 & C++11: 13.5/3]:
The following operators cannot be overloaded:. .* :: ?:
Solution 2:
In C++, there's a list of predefined operators, most of which are overloadable (.* is not). Additionally, any name can be used as an operator like:
#include <iostream>
// generic LHSlt holder
template<typename LHS, typename OP>
struct LHSlt {
LHS lhs_;
};
// declare myop as an operator-like construct
enum { myop };
// parse 'lhs <myop' into LHSlt
template<typename LHS>
LHSlt<LHS, decltype(myop)> operator<(const LHS& lhs, decltype(myop))
{
return { lhs };
}
// declare (int <myop> int) -> int
int operator>(LHSlt<int, decltype(myop)> lhsof, int rhs)
{
int& lhs = lhsof.lhs_;
// here comes your actual implementation
return (lhs + rhs) * (lhs - rhs);
}
// strictly optional
#define MYOP <myop>
int main() {
std::cout << (5 <myop> 2) << ' ' << (5 MYOP 2);
}
Disclaimer: This, strictly speaking, gets translated to (5 < myop) > 2
, which is LHSlt<int, decltype(myop)>(5) > 2
. Thus it's not a new 'operator', in C++-terms, but it's used exactly the same way, even in terms of ADL. Also, if type is large, you probably want to store const T&
.
Note that you can do this with any binary operator that can be defined external to the class; precedence is based on the precedence of the two sides (<
and >
). Thus you can have e.g. *myop*
, +myop+
, <<myop>>
, <myop>
, |myop|
in this order of precedence.
If you want right-associativity, it gets a bit more tricky. You'll need both of a RHS-holder and LHS-holder (the latter being LHSlt
here) and use surrounding operators such that the right one has higher precedence than the left one, e.g. a |myop> b |myop>c
is a |myop> (b |myop> c)
. Then you need the function for both your type and your holder type as the lhs.