【问题标题】:Generic math operator overloading without copying [duplicate]通用数学运算符重载而不复制[重复]
【发布时间】:2021-02-11 23:12:08
【问题描述】:

在阅读this 之后,我会有一个关于重载数学运算符的类似问题。

考虑到这个代码基础,它假设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 的实现来处理 &amp;NoCopy&lt;T&gt; 并提供一个 NoCopy&lt;O&gt; 实例,假设为 &amp;T 提供了 Add 运算符(并给出了一个 O)。 T 不需要尊重 Copy 特征。

但我不知道怎么写,尤其是泛型绑定。

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

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

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

【问题讨论】:

    标签: generics math rust


    【解决方案1】:

    您可以对&amp;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)
        }
    }
    

    (playground)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-02-25
      • 2015-06-20
      • 2015-08-22
      • 1970-01-01
      • 2013-11-30
      • 1970-01-01
      • 1970-01-01
      • 2011-10-27
      相关资源
      最近更新 更多