can't access an alias created inside an if statement

Simen Kjærås simen.kjaras at gmail.com
Wed Aug 5 09:25:23 UTC 2020


On Wednesday, 5 August 2020 at 09:05:36 UTC, Flade wrote:
> I have used an if-else statement to create an alias to avoid 
> code duplication but it doesn't let me access it outside the if 
> statement. Is there a way to solve this?

You're probably looking for static if:

     static if (useAlias) {
         alias myAlias = getAlias!();
     }

     myAlias foo = getFoo();


What happens is a regular if statement introduces a scope, so 
anything declared inside it is unavailable outside. static if 
does not introduce a new scope, and so its contents can be 
accessed.

static if only works with compile-time constant conditions, but 
aliases are also compile-time constructs, so this should not pose 
a problem.

--
   Simen


More information about the Digitalmars-d-learn mailing list