static interface

Simen kjaeraas simen.kjaras at gmail.com
Thu Nov 19 03:47:08 PST 2009


Leandro Lucarella <llucax at gmail.com> wrote:

> What do you think?

I was inspired:

template staticInterface( T, iface ) {
	static assert( is( iface == interface ) );
	static assert( is( T == struct ) );
	alias staticInterfaceImpl!( T, MemberTuple!( iface ) ) staticInterface;
}

template staticInterfaceImpl( T, U... ) {
	static if ( U.length ) {
		enum staticInterfaceImpl = isIn!( U[ 0 ], U[ 1 ], MemberTuple!( T ) ) &&  
staticInterfaceImpl!( T, U[ 2..$ ] );
	} else {
		enum staticInterfaceImpl = true;
	}
}

template MemberTuple( T ) {
	alias allMembersToTypeTuple!( T, __traits( allMembers, T ) ) MemberTuple;
}

template allMembersToTypeTuple( T, alias U, V... ) {
	static if( U.length ) {
		alias allMembersToTypeTuple!( T, U[1..$], U[ 0 ], typeof( mixin(  
T.stringof ~ "." ~ U[ 0 ] ) ), V ) allMembersToTypeTuple;
	} else {
		alias V allMembersToTypeTuple;
	}
}

template isIn( string name, T, U... ) {
	static if ( U.length ) {
		enum isIn = ( name == U[ 0 ] && is( T == U[ 1 ] ) ) || isIn!( name, T,  
U[ 2..$ ] );
	} else {
		enum isIn = false;
	}
}

Usage:

interface I;
struct S;
static if ( staticInterface!( S, I ) ) {}

There may be problems with this, and it might not match everything as  
nicely as it should, but it's a proof-of-concept. I'm open to suggestions  
on how to extend/fix it.

-- 
Simen



More information about the Digitalmars-d mailing list