在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,用于存储与该宏匹配的一组函数参数的值。例如,宏可能包含args foo: i32, bar: &Vec<String>,结果结构应该是:
struct GeneratedStruct {
foo: i32,
bar: Vec<String>,
}发布于 2017-02-07 00:41:19
正如Matthieu M.和kennytm在评论中建议的那样,您可以定义一个特征并使用特殊化(从Rust1.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>();
}https://stackoverflow.com/questions/42067701
复制相似问题