March 04, 2012 Re: How to avoid code duplication in static if branches? | ||||
---|---|---|---|---|
| ||||
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.
|
Copyright © 1999-2021 by the D Language Foundation