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

假设您有类似以下的类型:
struct Value(int v_)
{
  static const v = v_:
}
假设界面如下所示,您将如何对这些类型的列表进行排序:
alias Sorted!(Value!(4), Value!(2), Value!(1), Value!(3)) SortedValues;
如果能够提供更好的解决方案,您可以使用D 2.x功能,但如果您这样做,请说明。 我会在一天左右发布我的解决方案。 :)     
已邀请:
使用D 1.0,有一个QuickSort! http://paste.dprogramming.com/dplgp5ic     
顺便说一下,除非你有其他理由这样做,否则不需要将值包装在结构中,因为元组也可以正常工作。
alias Sorted!(4, 2, 1, 3) SortedValues;
    
这是我的解决方案。注意和FeepingCreature一样酷,但可能更容易理解;它通过递归地将第一种类型插入列表的其余部分(在对其进行排序之后)来工作。
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..." );
    

要回复问题请先登录注册