4

假设您有如下类型:

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

假设接口如下所示,您将如何对这些类型的列表进行排序:

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

如果可以提供更好的解决方案,您可以使用 D 2.x 功能,但请说明您是否这样做。

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

4

3 回答 3

3

使用 D 1.0,进行快速排序!

http://paste.dprogramming.com/dplgp5ic

于 2009-04-21T05:56:04.753 回答
1

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

alias Sorted!(4, 2, 1, 3) SortedValues;
于 2009-04-21T06:02:09.090 回答
-1

这是我的解决方案。注意与FepingCreature 一样酷,但可能更容易理解;它通过递归地将第一种类型插入到列表的其余部分(在对其进行排序之后)来工作。

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..." );
于 2009-04-22T11:22:19.357 回答