是否有任何允许运算符优先级重载的语言?

时间:2014-10-16 15:01:13

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

考虑这个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是。是否存在将根据变量类型选择运算符优先级规则的语言?

1 个答案:

答案 0 :(得分:0)

事实证明,我最初的问题实际上可以用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;
}

当然,无视这样的括号是一个可怕的想法。