How to avoid code duplication in static if branches?
Mantis
mail.mantis.88 at gmail.com
Sat Mar 3 18:02:06 PST 2012
04.03.2012 3:42, Andrej Mitrovic пишет:
> [...code...]
> I want to avoid writing "check()" twice. I only have to statically
> check a field of a member if it's of a certain type (Foo).
>
> One solution would be to use a boolean:
> void test(T)(T t)
> {
> bool isTrue = true;
> static if (is(T == Foo))
> isTrue = t.isTrue;
>
> if (isTrue)
> check();
> }
>
> But that kind of defeats the purpose of static if (avoiding runtime
> overhead). Does anyone have a trick up their sleeve for these types of
> situations? :)
>
Alias maybe?
void test(T)( T t ) {
enum TRUE = true;
static if( is(T == Foo) ) {
alias t.isTrue isTrue;
} else {
alias TRUE isTrue;
}
if( isTrue ) {
check();
}
}
This will still insert a redundant check for one of instantiations, but
compiler should be able to deal with 'if(true)' checks.
More information about the Digitalmars-d-learn
mailing list