8

在 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 的相关提案

4

1 回答 1

6

最小意外原则很重要,a*b *power* c * d评估为是关键a* (b^c) *d。幸运的是,有一个简单的解决方案。

为了确保它*power*比乘法具有更高的优先级,您必须使用类似的命名运算符技术进行乘法运算。

然后,您无需直接计算 and 的结果*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 语法单子解耦和/或违反标准。也许试试 Haskell?

于 2016-04-01T14:58:10.773 回答