【发布时间】:2021-02-12 22:33:53
【问题描述】:
我正在尝试使用特征和运算符重载在 Rust 中实现 C++ 样式的表达式模板。我在尝试为每个表达式模板结构重载“+”和“*”时陷入困境。编译器抱怨 Add 和 Mul trait 实现:
error[E0210]: type parameter `T` must be used as the type parameter for some local type (e.g., `MyStruct<T>`)
--> src/main.rs:32:6
|
32 | impl<T: HasValue + Copy, O: HasValue + Copy> Add<O> for T {
| ^ type parameter `T` must be used as the type parameter for some local type
|
= note: implementing a foreign trait is only possible if at least one of the types for which it is implemented is local
= note: only traits defined in the current crate can be implemented for a type parameter
如果我尝试为其实现特征的类型在没有我的 crate 的情况下可构造,那么该错误将是有意义的,但该类型是必须实现我定义的 HasValue 特征的泛型。
代码如下:
use std::ops::{Add, Mul};
trait HasValue {
fn get_value(&self) -> i32;
}
// Val
struct Val {
value: i32,
}
impl HasValue for Val {
fn get_value(&self) -> i32 {
self.value
}
}
// Add
struct AddOp<T1: HasValue + Copy, T2: HasValue + Copy> {
lhs: T1,
rhs: T2,
}
impl<T1: HasValue + Copy, T2: HasValue + Copy> HasValue for AddOp<T1, T2> {
fn get_value(&self) -> i32 {
self.lhs.get_value() + self.rhs.get_value()
}
}
impl<T: HasValue + Copy, O: HasValue + Copy> Add<O> for T {
type Output = AddOp<T, O>;
fn add(&self, other: &O) -> AddOp<T, O> {
AddOp {
lhs: *self,
rhs: *other,
}
}
}
// Mul
struct MulOp<T1: HasValue + Copy, T2: HasValue + Copy> {
lhs: T1,
rhs: T2,
}
impl<T1: HasValue + Copy, T2: HasValue + Copy> HasValue for MulOp<T1, T2> {
fn get_value(&self) -> i32 {
self.lhs.get_value() * self.rhs.get_value()
}
}
impl<T: HasValue + Copy, O: HasValue + Copy> Mul<O> for T {
type Output = MulOp<T, O>;
fn mul(&self, other: &O) -> MulOp<T, O> {
MulOp {
lhs: *self,
rhs: *other,
}
}
}
fn main() {
let a = Val { value: 1 };
let b = Val { value: 2 };
let c = Val { value: 2 };
let e = ((a + b) * c).get_value();
print!("{}", e);
}
想法?
【问题讨论】:
标签: rust