在C++ 11中,您可以将泛型类型衰减为值类型,删除引用/右值语义和cv限定符,例如
decay<int>::type // type is `int`
decay<const int&>::type // type is `int`
decay<int&&>::type // type is `int`
Run Code Online (Sandbox Code Playgroud)
是否有一种已知的机制可以在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`
Run Code Online (Sandbox Code Playgroud)
对于背景,我正在尝试编写一个宏,该宏生成一个struct存储宏匹配的一堆函数参数的值.例如,宏可能包含args foo: i32, bar: &Vec<String>,结果结构应该是:
struct GeneratedStruct {
foo: i32,
bar: Vec<String>,
}
Run Code Online (Sandbox Code Playgroud)
正如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>();
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
145 次 |
| 最近记录: |