首页 > 解决方案 > 通用数学运算符重载而不复制

问题描述

读完这篇文章后,我会有一个关于重载数学运算符的类似问题。

考虑到这个代码基础,它假设T对象可以按值添加并给出O

use std::ops::Add;

struct NoCopy<T>(T);

impl<T: Add<Output = O>, O> Add for NoCopy<T> {
    type Output = NoCopy<O>;

    fn add(self, other: Self) -> Self::Output {
        NoCopy(self.0 + other.0)
    }
}

fn main() {
    let a = NoCopy::<isize>(5);
    let b = NoCopy::<isize>(3);

    let _c = a + b;
}

我想提供一个 Add trait 的实现来处理&NoCopy<T>并提供一个NoCopy<O>实例,假设提供了 Add 运算符&T(并给出 a O)。T不需要尊重该Copy特征。

但我不知道如何编写它,尤其是泛型绑定。

impl<???> Add for &NoCopy<T> {
    type Output = NoCopy<O>;

    fn add(self, other: Self) -> Self::Output {
        NoCopy(&self.0 + &other.0)
    }
}

缺少的部分 ( ???) 会是什么样子?

标签: genericsmathrust

解决方案


您可以在以下位置设置生命周期约束&T

impl<'a, T: 'a, O> Add for &'a NoCopy<T>
where
    &'a T: Add<Output = O>,
{
    type Output = NoCopy<O>;

    fn add(self, other: Self) -> Self::Output {
        NoCopy(&self.0 + &other.0)
    }
}

操场


推荐阅读