如何为本地特征实现 std::ops::Add?
How to implement std::ops::Add for a local trait?
我有实现特征的对象:
trait X {
fn transform_a(&self) -> Self;
fn transform_b(&self) -> Self;
}
我想使用一些形式为 obj + Transform::A + Transform::B
的语法糖,所以我尝试了:
enum Transform {
A, B
}
impl<T> std::ops::Add<Transform> for T where T: X {
type Output = T;
fn add(self, rhs: Transform) -> T {
match rhs {
Transform::A => self.transform_a(),
Transform::B => self.transform_b(),
}
}
}
这行不通。我收到错误:
10 | impl<T> std::ops::Add<Transform> for T where T: X {
| ^ type parameter `T` must be covered by another type when it appears before the first local type (`Transform`)
|
= note: implementing a foreign trait is only possible if at least one of the types for which is it implemented is local, and no uncovered type parameters appear before that first local type
= note: in this case, 'before' refers to the following order: `impl<..> ForeignTrait<T1, ..., Tn> for T0`, where `T0` is the first and `Tn` is the last
错误似乎说这是不可能的。如果可能,如何实现?
正如 E0210 上的文档向我指出的那样,不,这是不可能的。
我有实现特征的对象:
trait X {
fn transform_a(&self) -> Self;
fn transform_b(&self) -> Self;
}
我想使用一些形式为 obj + Transform::A + Transform::B
的语法糖,所以我尝试了:
enum Transform {
A, B
}
impl<T> std::ops::Add<Transform> for T where T: X {
type Output = T;
fn add(self, rhs: Transform) -> T {
match rhs {
Transform::A => self.transform_a(),
Transform::B => self.transform_b(),
}
}
}
这行不通。我收到错误:
10 | impl<T> std::ops::Add<Transform> for T where T: X {
| ^ type parameter `T` must be covered by another type when it appears before the first local type (`Transform`)
|
= note: implementing a foreign trait is only possible if at least one of the types for which is it implemented is local, and no uncovered type parameters appear before that first local type
= note: in this case, 'before' refers to the following order: `impl<..> ForeignTrait<T1, ..., Tn> for T0`, where `T0` is the first and `Tn` is the last
错误似乎说这是不可能的。如果可能,如何实现?
正如 E0210 上的文档向我指出的那样,不,这是不可能的。