simple static if / traits question...
Profile Anaysis via Digitalmars-d-learn
digitalmars-d-learn at puremagic.com
Wed Feb 22 14:37:25 PST 2017
On Wednesday, 22 February 2017 at 21:27:47 UTC, WhatMeWorry wrote:
>
>
> I'm doing conditional compilation using static ifs like so:
>
> enum bool audio = true;
>
>
>
> // if audio flag is present and set to true, add to code build
>
> static if ( (__traits(compiles, audio)) && audio)
> playSound(soundSys, BLEEP );
>
>
> This works, but I thought there might be a simpler way. For
> instance,
> after perusing std.traits, I thought I would find something like
> isPresent(audio) or isSymbol(audio) templates.
>
> Or am I being obtuse here?
>
> Thanks.
You do realize that audio is a compile time constant? This means
that in the binary, everything that depends on it is evaluated(as
it can be, since it is known). This means that whatever app you
are using will not be able to be able to "adapt" to the system
changes. In this case, if the system has audio there is no way
for the binary to use it because you compiled it out(if audio =
false).
In such a case you do not want to use a static or compile time
variable unless you plan on creating multiple binaries.
If your example above was just for demo then yes, you can do that
but compiles is not what you want. Compiles only checks if the
statement that follows is compilable as valid D code and it
doesn't have anything to do with the value of the variables.
There are a few options:
1. static if(audio)
2. version(audio)
3. if (audio)
It looks like you are trying to create the version(audio)
semantic(if exists then use, else don't).
Ultimately, though, if you are trying to make a binary that can
either use audio or not depending on where it is ran, you'll have
to stick to using actual run time variables and probably be a bit
more organized about it.
More information about the Digitalmars-d-learn
mailing list