Conditional Compilation Multiple Versions
Mike Parker via Digitalmars-d-learn
digitalmars-d-learn at puremagic.com
Fri Jan 6 05:27:06 PST 2017
Glad hear it's working for you!
On Friday, 6 January 2017 at 10:25:26 UTC, Claude wrote:
> So I had a stream of:
>
> version (Win32)
> enum bool WindowsSupported = true;
> else
> enum bool WindowsSupported = false;
>
> version (Win64)
> enum bool WindowsSupported = true; //Ooops
> else
> enum bool WindowsSupported = false; //Ooops
These can be condensed to:
version(Win32)
enum bool WindowsSupported = true;
else version(Win64)
enum bool WindowsSupported = true;
else
enum bool WindowsSupported = false;
Or even better, since it doesn't appear you need to distinguish
between 32-bit & 64-bit:
version(Windows)
enum bool WindowsSupported = true;
else
enum bool WindowsSupported = false;
>
> It turned out to be not so readable (even when using a "string
> mixin" to make the code tighter), and I cannot define twice an
> enum without using "static if", which was a deal-breaker. Also
> the conciseness of the versions for the D compilers (only 4:
> DMD, GDC, LDC and SDC), as well as the different OS versions
> made the code a lot tighter than the C version.
For me, the readability is no issue. I would put that block above
in a single module (which I like to call config.d) and then
import it where I need it. This actually is a lot cleaner for the
corner cases where version breaks down (see below).
>
> So I just dropped the enum definition thing and just used
> "version" as it was designed to be used:
>
> version (Win32)
> version = WindowsSupported;
> else version (Win64)
> version = WindowsSupported;
> else etc...
version(Windows) { }
>
> That little experience showed that using version as it is
> designed currently is enough to elegantly cover my needs. And
> it seemed to scale well.
> Also I think it may force developers to handle all version
> specific stuff into one specific module and define your own
> version identifiers to list features from compiler, OS, target
> architecture version identifiers; which is a good coding
> practice anyway.
>
Yes, it works quite well for most use cases and should generally
be preferred. I disagree that it scales, though. At some point (a
point that is highly project-dependent), it breaks down,
requiring either very large modules or duplicated versions across
multiple modules.
My position is that I will always choose version blocks first,
but if I find myself in a situation where I have to choose
between duplicating version statements (e.g. version(A)
{version=AorB; version=AorC;}) across multiple modules and
restructuring my code to accommodate versioning, I much prefer to
use the enum alternative as an escape hatch.
More information about the Digitalmars-d-learn
mailing list