题
假定有一个类型如下所示:
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,具有快速排序!
其他提示
通过,除非你有其他原因的方式做它没有必要来包装结构的值作为元组工作得很好,其值也是如此。
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..." );
不隶属于 StackOverflow