It is easy to introduce new infix operators in C++
// User-defined infix operator framework
template <typename LeftOperand, typename Operation>
struct LeftHelper
{
const LeftOperand& leftOperand;
const Operation& operation;
LeftHelper(const LeftOperand& leftOperand,
const Operation& operation)
: leftOperand(leftOperand), operation(operation) {}
};
template <typename LeftOperand, typename Operation >
auto operator < (const LeftOperand& leftOperand,
Operation& operation)
{
return LeftHelper<LeftOperand, Operation>(leftOperand, operation);
}
template <typename LeftOperand, typename Operation, typename RightOperand>
auto operator > (LeftHelper<LeftOperand, Operation> leftHelper,
const RightOperand& rightOperand)
{
return leftHelper.operation(leftHelper.leftOperand, rightOperand);
}
// Defining a new operator
#include <cmath>
static auto pwr = [](const auto& operand1, const auto& operand2) { return std::pow(operand1, operand2); };
// using it
#include <iostream>
int main()
{
std::cout << (2 <pwr> 16) << std::endl;
return 0;
}
Unfortunately, this power operator has wrong precedence and associativity. So my question is: how to fix this? I want my <pow>
to have higher precedence than *
and associate to the right, just like in the mathematical notation.
Edit It is possible to vary the precedence by using different brackets, e.g. |op|
, /op/
, *op*
or even, if one is so inclined, <<--op-->>
, but one cannot go higher than the highest built-in operator precedence this way. But today C++ is so powerful with template metaprogramming and type deduction, there simply ought to be some other way to achieve the desired result.
Additionally, it would be nice if I could use pow
and not pwr
. Unfortunately in some implementations #include <cmath>
brings pow
into the global namespace, so there will be a conflict. Can we overload operator not
such that a declaration of the form
not using std::pow;
removed std::pow
from the global namespace?
Further reading: a related proposal by Bjarne Stroustrup.
while(i ----> 0)
. Very handy! – Failing-
. I wouldn't be surprised if someone made something awesome with this operator definition thing in some math library. – Validity