【发布时间】: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 的实现来处理 &NoCopy<T> 并提供一个 NoCopy<O> 实例,假设为 &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)
}
}
缺少的部分 (???) 会是什么样子?
【问题讨论】: