简体   繁体   English

如何为本地特征实现 std::ops::Add?

[英]How to implement std::ops::Add for a local trait?

I have objects implementing a trait:我有实现特征的对象:

trait X {
    fn transform_a(&self) -> Self;
    fn transform_b(&self) -> Self;
}

I'd like to use some syntactic sugar of the form obj + Transform::A + Transform::B , so I tried:我想使用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(),
        }
    }
}

This doesn't work.这是行不通的。 I get the error:我收到错误:

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

The error seems to say this is impossible.该错误似乎说这是不可能的。 How to accomplish this, if possible?如果可能的话,如何做到这一点?

Playground 操场

As pointed out to me via the documentation on E0210, no , this is not possible.正如通过 E0210 上的文档向我指出的那样,,这是不可能的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM