c++11 - Rust 中的 C+11 类类型衰减

标签 c++11 macros rust

在 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/

相关文章:

c++ - 宏中的换行符 #

docker - 使用 Rust 访问 google cloud run (docker) 中的环境变量的适当方法

rust - 为什么这个闭包没有实现Fn?

c++ - 如果给定的模板不是专门用于运算符参数类型,则禁用运算符重载

macros - 导致不卫生的宏的单个 namespace 是什么? (在 LISP 中)

c++ - std::bind 有多少个参数(VC 11 只支持 4 个)

regex - 当替换器使用变量时,如何调用 Regex::replace_all?

rust - rss crate 已安装,但找不到函数 Channel::from_url

c++ - std::chrono 添加天数到当前日期

function - 为什么要编写一个带有名称的 C++ lambda 以便可以从某个地方调用它?