代码之家  ›  专栏  ›  技术社区  ›  DK.

D模板:对类型列表进行排序

  •  4
  • DK.  · 技术社区  · 17 年前

    struct Value(int v_)
    {
      static const v = v_:
    }
    

    假设有这样一个接口,您将如何对这些类型的列表进行排序:

    alias Sorted!(Value!(4), Value!(2), Value!(1), Value!(3)) SortedValues;
    

    我将在一天左右后发布我的解决方案。:)

    3 回复  |  直到 17 年前
        1
  •  3
  •   FeepingCreature    17 年前

    使用D1.0,进行快速排序!

    http://paste.dprogramming.com/dplgp5ic

        2
  •  1
  •   BCS    17 年前

    顺便说一句,除非您有其他理由这样做,否则没有必要将值包装到结构中,因为元组也可以很好地处理值。

    alias Sorted!(4, 2, 1, 3) SortedValues;
    
        3
  •  -1
  •   DK.    17 年前

    module sort;
    
    /*
     * Tango users substitute "tango.core.Tuple" for "std.typetuple" and "Tuple"
     * for "TypeTuple".
     */
    
    import std.typetuple;
    
    struct Val(string v_)
    {
        static const v = v_;
    }
    
    template Sorted_impl(T)
    {
        alias TypeTuple!(T) Sorted_impl;
    }
    
    template Sorted_impl(T, U, V...){
    
        static if( T.v < U.v )
            alias TypeTuple!(T, U, V) Sorted_impl;
    
        else
            alias TypeTuple!(U, Sorted_impl!(T, V)) Sorted_impl;
    }
    
    template Sorted(T)
    {
        alias TypeTuple!(T) Sorted;
    }
    
    template Sorted(T, U...)
    {
        alias Sorted_impl!(T, Sorted_impl!(U)) Sorted;
    }
    
    pragma(msg, Sorted!(Val!("a")).stringof);
    
    pragma(msg, Sorted!(Val!("b"), Val!("a")).stringof);
    
    pragma(msg, Sorted!(
        Val!("d"), Val!("a"), Val!("b"), Val!("c")
    ).stringof);
    
    static assert( false, "nothing to compile here, move along..." );