2009-04-21 77 views
4

列表假设你有一个类型如下所示:d模板:那种类型

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

你会如何排序这些类型的列表,假定一个接口是这样的:

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

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

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

回答

1

通过,除非你有其他的原因这样做没有必要来包装结构的值作为元组的工作只是罚款与价值观以及方式。

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

正确;但我相信元组会打破别名。使用包装器结构只是我能想到的更一般的问题形式。 :) – 2009-04-21 06:11:19

-1

这是我的解决方案。注意与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...");