【问题标题】:Are there any languages which allow operator precedence to be overloaded?是否有任何语言允许重载运算符优先级?
【发布时间】:2014-12-12 00:16:27
【问题描述】:

考虑一下这个 C++ 代码:

struct A {
    A operator*(A a) { return A(); }  // A*A -> A
};
struct B {
    A operator*(B b) { return A(); }  // B*B -> A
};

int main() {
    A t2 = B()*B() * A(); // works
    A t1 = A() * B()*B(); // errors
    return 0;
}

A*B 是不允许的,但B*B 是。是否存在根据变量类型选择运算符优先级规则的语言?

【问题讨论】:

  • 我当然希望不会——我很同情那些调试解析器的人。
  • @larsmans:我认为这句话起源于一个匿名的 c++ 编译器作者会议。
  • @phimuemue 但是类型会改变 ALGOL 中的优先级吗?否则,就像 Prolog 一样,您可以设置优先级但以后不能更改。
  • 存在可以使用括号来确定操作顺序的程序员。

标签: c++ operator-overloading operator-precedence


【解决方案1】:

原来我原来的问题其实可以用C++来表达:

struct A {
    friend A operator*(A const& a1, A const &a2) { return A(); }  // A*A -> A
};
struct B {
    friend A operator*(B const& a, B const &b) { return A(); }  // B*B -> A
};

template<typename A, typename B>
struct unresolved_multiply {
    A const& a;
    B const& b;
};

template<typename A, typename B>
unresolved_multiply<A, B> operator*(A const& a, B const &b) {
    return {a, b};
}

template<typename A, typename B, typename C>
auto operator*(unresolved_multiply<A, B> const& ab, C const &c) {
    return ab.a * (ab.b * c);
}

int main() {
    A t1 = B()*B() * A();   // works
    A t2 = A() * B()*B();   // works
    A t3 = (A() * B())*B(); // works...
    return 0;
}

当然,像这样忽略括号是个糟糕的主意。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-10-08
    • 1970-01-01
    • 2013-06-26
    • 1970-01-01
    • 2017-07-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多