代码之家  ›  专栏  ›  技术社区  ›  ssb

如何在Rust中复制C++基于模板的SFINAE模式?

  •  0
  • ssb  · 技术社区  · 6 年前

    我有以下资料:

    trait Runnable {
        fn run(&self);
    }
    
    struct Foo<T> {
        // Something
    }
    
    impl<T> Runnable for Foo<T>
    where
        T: Send + Sync,
    {
        fn run(&self) {}
    }
    
    impl<T> Runnable for Foo<T>
    where
        T: Send + ?Sync,
    {
        fn run(&self) {}
    }
    

    impl 即使 T 在两种情况下都是相互排斥的:

    error[E0119]: conflicting implementations of trait `Runnable` for type `Foo<_>`:
      --> src/main.rs:16:1
       |
    9  | / impl<T> Runnable for Foo<T>
    10 | | where
    11 | |     T: Send + Sync,
    12 | | {
    13 | |     fn run(&self) {}
    14 | | }
       | |_- first implementation here
    15 | 
    16 | / impl<T> Runnable for Foo<T>
    17 | | where
    18 | |     T: Send + ?Sync,
    19 | | {
    20 | |     fn run(&self) {}
    21 | | }
       | |_^ conflicting implementation for `Foo<_>`
    
    1 回复  |  直到 6 年前
        1
  •  4
  •   mcarton    6 年前

    #![feature(specialization)]
    
    trait Runnable {
        fn run(&self);
    }
    
    struct Foo<T> {
        _t: T,
    }
    
    impl<T> Runnable for Foo<T>
    where
        T: Send + Sync,
    {
        fn run(&self) {}
    }
    
    impl<T> Runnable for Foo<T>
    where
        T: Send,
    {
        default fn run(&self) {}
    //  ^^^^^^^ this is the magic you need
    }
    
    fn main() {}
    

    但是,从Rust 1.26.2开始,专门化并不稳定,需要每晚编译一次。