generics - 通用数学运算符重载而不复制
问题描述
读完这篇文章后,我会有一个关于重载数学运算符的类似问题。
考虑到这个代码基础,它假设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)
}
}
缺少的部分 ( ???
) 会是什么样子?
解决方案
您可以在以下位置设置生命周期约束&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)
}
}
(操场)
推荐阅读
- amazon-s3 - s3:putObject 的跨账户权限未按预期工作
- pandas - how to plot a dataframe with two different axes in pandas matplotlib
- r - tidyverse:readr read_delim 遇到制表符和分号错误?
- bash - 用于检索文件名的 BASH 字符串运算符语法
- youtube - 查询 YouTube API 以获得最喜欢的视频
- c# - 使用 Unity 框架进行 Leap 运动中的光标
- tensorflow - Tensorflow:在恢复的元图中用真实张量替换占位符
- ios - iOS 11.4 仅请求 .well-known/apple-app-site-association
- javascript - 为 Redux-Form Wizard 制作自定义单选按钮
- mule - 在 mule 4 中需要管道分隔文本文件到 json 的帮助