在 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;
}
不幸的是,这个幂运算符有错误的优先级和关联性。所以我的问题是:如何解决这个问题?我希望我<pow>
的优先级高于*
并关联到右边,就像在数学符号中一样。
编辑可以通过使用不同的括号来改变优先级,例如|op|
, /op/
,*op*
或者甚至,如果一个人如此倾向于,<<--op-->>
,但是这样不能高于最高的内置运算符优先级。但是今天 C++ 在模板元编程和类型推导方面如此强大,应该有一些其他的方法来达到预期的结果。
此外,如果我可以使用pow
而不是pwr
. 不幸的是,在某些实现中#include <cmath>
引入pow
了全局命名空间,因此会有冲突。我们可以重载operator not
这样的形式声明
not using std::pow;
std::pow
从全局命名空间中删除?
进一步阅读:Bjarne Stroustrup 的相关提案。