首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >铁锈中的类C+11衰变

铁锈中的类C+11衰变
EN

Stack Overflow用户
提问于 2017-02-06 20:21:54
回答 1查看 179关注 0票数 4

在C++11中,您可以将泛型类型衰减为值类型,删除引用/右值语义和cv限定符,例如

代码语言:javascript
复制
decay<int>::type // type is `int`
decay<const int&>::type // type is `int`
decay<int&&>::type // type is `int`

是否有一种已知的机制可以在Rust中实现相同的功能,即剥离引用修饰符、生命周期和mut限定符?例如:

代码语言:javascript
复制
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>,结果结构应该是:

代码语言:javascript
复制
struct GeneratedStruct {
    foo: i32,
    bar: Vec<String>,
}
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2017-02-07 00:41:19

正如Matthieu M.kennytm在评论中建议的那样,您可以定义一个特征并使用特殊化(从Rust1.15.0开始是一个不稳定的特性)来实现这一点。

代码语言:javascript
复制
#![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>();
}
票数 5
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/42067701

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档