D Templates: sort a list of types

Suppose you have a type such as:

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

How would you sort the list of these types, assuming an interface something like this:

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

You can use the functions of D 2.x if it offers a better solution, but please indicate if you will.

I will send my decision in a day or so. :)

+4
source share
3 answers

Using D 1.0, use QuickSort!

http://paste.dprogramming.com/dplgp5ic

+3
source

By the way, unless you have other reasons for this, there is no need to wrap the value in structs, since tuples work just fine with the values.

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

Here is my solution. Note that this is cool, like FeepingCreature, but probably easier to understand; it works by recursively inserting the first type into the rest of the list (after sorting it).

 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( Tv < Uv ) 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..." ); 
-1
source

All Articles