Handy templates

Simen kjaeraas simen.kjaras at gmail.com
Wed May 26 16:00:36 PDT 2010


Here's a collection of templates I have created and use often. Some of  
these may be fit for inclusion in Phobos, others maybe not as much.
Please critique, and post your own indispensable snippets.

/**
Checks if one tuple contains another.

Example:
----
static assert(Contained!(int).In!(float, int));
static assert(!Contained!(int).In!(float, "foo"));
static assert(Contained!(int,"foo").In!(float, int, "foo", "bar"));
----
  */
template Contained(T...) {
     template In(U...) {
         static if (T.length == 0) {
             enum In = true;
         } else static if (U.length >= T.length) {
             enum In = SameTuple!(T).As!( U[0..T.length]) ||
                 Contained!(T).In!(U[1..$]);
         } else {
             enum In = false;
         }
     }
}

unittest {
     static assert(Contained!(int).In!(float, int));
     static assert(!Contained!(int).In!(float, "foo"));
     static assert(Contained!(int,"foo").In!(float, int, "foo", "bar"));
     static assert(!Contained!(int,"foo").In!(float, int, "bar", "foo"));
     static assert(Contained!().In!(float, int, "bar", "foo"));
}


/**
Evaluates to $(D F!(T[0..tupleLength]) &&  
F!(T[tupleLength..2*tupleLength]) && ... && F[T[$-tupleLength..$]]).

Example:
----
     static assert(allTuplesSatisfy!(Contained!(int).In, 2, int, float,  
"foo", int));
     static assert(!allTuplesSatisfy!(Contained!(int).In, 2, int, float,  
"foo",string));
----
  */
template allTuplesSatisfy( alias F, uint tupleLength, T... ) {
     static assert( !( T.length % tupleLength ) );

     static if ( T.length == tupleLength ) {
         enum allTuplesSatisfy = F!( T );
     } else {
         enum allTuplesSatisfy = F!( T[0..tupleLength] ) &&  
allTuplesSatisfy!( F, tupleLength, T[tupleLength..$] );
     }
}

unittest {
     static assert(allTuplesSatisfy!(Contained!(int).In, 2, int, float,  
"foo", int));
     static assert(!allTuplesSatisfy!(Contained!(int).In, 2, int, float,  
"foo",string));
}

/**
Repeats a type or tuple $(D num) times.

Example:
----
     static assert(allTuplesSatisfy!(Contained!(int).In, 2, int, float,  
"foo", int));
     static assert(!allTuplesSatisfy!(Contained!(int).In, 2, int, float,  
"foo",string));
----
  */
template Repeat( uint num, T... ) {
     static if ( num > 1 ) {
         alias TypeTuple!( T, Repeat!( num -1, T ) ) Repeat;
     } else {
         alias T Repeat;
     }
}

unittest {
     static assert(SameTuple!(Repeat!(4, int)).As!(int, int, int, int));
     static assert(SameTuple!(Repeat!(4, "foo")).As!("foo", "foo", "foo",  
"foo"));
     static assert(SameTuple!(Repeat!(2, int, "foo")).As!(int, "foo", int,  
"foo"));
     static assert(!SameTuple!(Repeat!(2, int)).As!());
}


-- 
Simen


More information about the Digitalmars-d-learn mailing list