我只是在学习Rust,希望编写使用泛型类型执行编译时算术的代码.
例如,在C++中,我可以编写以下代码(on Goldbolt):
#include <iostream>
template <int X>
struct Test {
constexpr static int x = X;
};
template <int X1, int X2>
auto operator+(const Test<X1>&, const Test<X2>&) {
return Test<X1 + X2>{};
}
int main() {
const Test<4> a{};
const Test<6> b{};
const auto c = a + b;
std::cout << c.x << '\n'; // prints 10
}
我试着用Rust(on Playground)编写类似的代码:
use std::ops::Add;
pub struct Test<const X: u8>;
impl<const X: u8> Test<X> {
pub fn x(&self) -> u8 { X }
}
impl<const X1: u8, const X2: u8> Add<Test<X2>> for Test<X1> {
type Output = Test<{X1 + X2}>;
fn add(self, rhs: Test<X2>) -> Test<{X1 + X2}> {
Test::<{X1 + X2}>{}
}
}
fn main() {
let a: Test<4> = Test{};
let b: Test<6> = Test{};
let c = a + b;
println!("{}", c::x());
}
...但这不会被编译,因为generic parameters may not be used in const operations
.这类事情对Rust 来说根本不可能,还是我可以try 另一种策略?