如何检查泛型类型是否实现了泛型特征?

炸鱼薯条德里克

我想检查一个类型是否实现了特征而不创建对象。但是它不能编译。请参阅代码中的注释。那我该怎么做才能达到目标呢?

#![feature(specialization)]

struct T1;
struct T2;

trait A {}

impl A for T1 {}

trait Get_Static<TraitType> {
    fn has_trait() -> bool ;
}
default impl<TraitType, T> Get_Static<TraitType> for T
{
    fn has_trait() -> bool { false }
}
impl<TraitType, T> Get_Static<TraitType> for T where T:TraitType
{
    fn has_trait() -> bool { true }
}//Compiler complains TraitType is not a trait but type parameter

fn main() {
    if <T1 as Get_Static>::<A>::has_trait() {println!("{}", true)} else {println!("{}", false)}
    if <T2 as Get_Static>::<A>::has_trait() {println!("{}", true)} else {println!("{}", false)}
//This is surely wrong syntax but I don't know the right syntax
}
马修M.

感谢Stefan抚平了最后的皱纹

<T2 as Get_Static>::<A>::has_trait()
  //This is surely wrong syntax but I don't know the right syntax

这尝试调用:

  • 特质相关功能
  • 为特定类型实现。

语法为<Type as Trait>::associated_function()在这种情况下,TypeT1TraitGet_Static<A>所以这应该是:

<T2 as Get_Static<A>>::has_trait()
impl<TraitType, T> Get_Static<TraitType> for T where T:TraitType
{
    fn has_trait() -> bool { true }
}
//Compiler complains TraitType is not a trait but type parameter

无法直接指出TraitType应为trait,但是Unsize可以使用标记检查是否T: Unsize<TraitType>足以满足我们的目的。

这需要3个更改:

  • #![feature(unsize)]Unsize标记不稳定时启用夜间功能
  • 允许Get_Static通用参数为?Sized,因为特征没有大小限制,
  • 使用T: Unsize<TraitType>如在实施约束。

总而言之,这意味着:

#![feature(specialization)]
#![feature(unsize)]

trait GetStatic<TraitType: ?Sized> {
    fn has_trait() -> bool ;
}

default impl<TraitType: ?Sized, T> GetStatic<TraitType> for T {
    fn has_trait() -> bool { false }
}

impl<TraitType: ?Sized, T> GetStatic<TraitType> for T 
    where
        T: std::marker::Unsize<TraitType>
{
    fn has_trait() -> bool { true }
}

然后用作:

struct T1;
struct T2;

trait A {}

impl A for T1 {}

fn main() {
    println!("{}", <T1 as GetStatic<A>>::has_trait());
    println!("{}", <T2 as GetStatic<A>>::has_trait());
}

在操场上观看比赛

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章