generalising template specialisation

Sean Kelly sean at f4.ca
Sat Nov 11 08:48:43 PST 2006


Thomas Kuehne wrote:
> -----BEGIN PGP SIGNED MESSAGE-----
> Hash: SHA1
> 
> I am going to use TemplateTypeParameterSpecialization in the samples
> below, all the ideas apply to TemplateValueParameterSpecialization too.
> 
> 
> Current specialisation:
> #
> # template A (T : SomeType) { /* ... */ }
> #
> 
> Template A matches if T is implicitly convertible to SomeType.
> 
> 
> How do you define a template that matches if T is a struct?
> #
> # template B (T) {
> #    static if(is(T == struct)) {
> #	/* ... */
> #    } else {
> #       static assert(0, "use a struct");
> #    }
> # }
> # 
> 
> OK that works, though the error will be reported on the assert line
> instead of the instantiation line.

This is where concept checking is really useful.  However, you can 
overload on concepts in D using something like the following:

struct ClassType {}
struct StructType {}
...

template TypeOf( T ) {
     static if( is( T == class ) )
         alias ClassType TypeOf;
     else static if( is( T == struct ) )
         alias StructType TypeOf;
     ...
}

template ClassTempl( T, Type : ClassType = TypeOf!(T) ) {
     // make sure the user didn't cheat
     static assert( is( Type == TypeOf!(T) );
     ...
}

template StructTempl( T Type : StructType = TypeOf!(T) ) {
     // make sure the user didn't cheat
     static assert( is( Type == TypeOf!(T) );
     ...
}

It's a bit messy, but it works.


Sean



More information about the Digitalmars-d mailing list