在 C++11 中,您可以将泛型类型衰减为值类型,移除引用/右值语义和 cv 限定符,例如
decay<int>::type // type is `int`
decay<const int&>::type // type is `int`
decay<int&&>::type // type is `int`
在 Rust 中是否有一种已知的机制可以实现相同的功能,即去除引用修饰符、生命周期和 mut
预选赛?例如:
decay<u32>::type <--- type is `u32`
decay<&u32>::type <--- type is `u32`
decay<&mut u32>::type <--- type is `u32`
decay<&static u32>::type <--- type is `u32`
作为背景,我正在尝试编写一个生成 struct
的宏它存储了一堆与宏匹配的函数参数的值。例如,宏可能包含参数 foo: i32, bar: &Vec<String>
,结果结构应该是:
struct GeneratedStruct {
foo: i32,
bar: Vec<String>,
}
最佳答案
根据 Matthieu M. 的建议和 kennytm在注释中,您可以定义一个特征并使用特化(从 Rust 1.15.0 开始是一个不稳定的特性)来实现这一点。
#![feature(specialization)]
use std::any::TypeId;
trait Decay {
type Type;
}
impl<T> Decay for T {
default type Type = T;
}
impl<'a, T> Decay for &'a T {
type Type = <T as Decay>::Type;
}
impl<'a, T> Decay for &'a mut T {
type Type = <T as Decay>::Type;
}
fn foo<T: 'static>() {
println!("{:?}", TypeId::of::<T>());
}
fn bar<T>() where <T as Decay>::Type: 'static {
println!("{:?}", TypeId::of::<<T as Decay>::Type>());
}
fn main() {
foo::<<i32 as Decay>::Type>();
foo::<<&i32 as Decay>::Type>();
foo::<<&mut i32 as Decay>::Type>();
foo::<<&&i32 as Decay>::Type>();
bar::<i32>();
bar::<&i32>();
bar::<&mut i32>();
bar::<&&i32>();
}
关于c++11 - Rust 中的 C+11 类类型衰减,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42067701/