很容易在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
?
答案 0 :(得分:6)
最少惊喜的原则很重要,a*b *power* c * d
评估a* (b^c) *d
是关键。幸运的是,有一个简单的解决方案。
为确保*power*
的优先级高于乘法,您必须使用类似的命名运算符技术进行乘法。
然后,您不是直接计算*power*
和*times*
的结果,而是构建表达式树。评估时,此表达式树可以应用任意优先级规则。
我们可以对每个内置运算符执行此操作,为我们提供易于阅读的语法,允许对运算符优先级进行编译时元编程:
auto z =equals= bracket<
a *plus* b *times* c *power* bracket<
a *plus* b
>bracket *power* x *times* y
>bracket;
为避免此表达式模板的存储时间超过最佳值,只需重载operator auto()&&
即可返回推导出的类型。如果您的编译器无法支持该功能,=equals=
可以以较低的清晰度成本返回正确的类型。
请注意,上述语法实际上可以使用类似于OP的技术在C ++中实现。实际实现大于SO帖子应包含的内容。
还有其他好处。众所周知,编程语言中隐藏的ASCII字符已经失宠,阅读C ++的人可能会被以下表达式所困扰:
int z = (a + b* pow(c,pow(x,a+b))*y);
使用这种技术,所有运算符都具有可读的名称,使其含义清晰,并且所有内容都使用中缀而不是混合中缀和前缀表示法。
确保pow
可用的类似解决方案可以通过自己重新实现<cmath>
<cmath_nopow>
来完成。这避免了操作符不会在语言结构上重载,这会导致AST语法monad解耦和/或违反标准。也许试试Haskell?