Good examples of version() algebra in real code
Walter Bright
newshound2 at digitalmars.com
Mon May 22 08:21:50 UTC 2023
On 5/21/2023 7:01 PM, Hipreme wrote:
> Right now I've come to understand that using feature based versions instead of
> real versions really makes a lot of difference. But as Guillaume pointed out,
> there is still this other problem of defining a feature based on multiple
> platforms and this solution doesn't really make one write a lot less, so I still
> find this solution lacking for our problem which makes me wonder if there really
> exists a good solution for that.
version(linux) enum ExtraFunctionality = true;
else version(OSX) enum ExtraFunctionality = true;
else version(Windows) enum ExtraFunctionality = false;
else static assert(0, "system not accounted for");
The static assert is there because a very common failure of #ifdef hell is to
have defaults that botch things up when a new version is added.
This happens sometimes in the druntime imports, when I discover them I add the
static assert.
There are still other ways to do it:
```
import extra;
void foo()
{
extraFunctionality();
}
```
```
module extra;
void extraFunctionality()
{
version(linux) doit();
else version(OSX) doit();
else version(Windows) { }
else static assert(0, "system not accounted for");
}
```
Another way is to write a "personality module" for each operating system, and
then import the right one:
```
module extra;
version (linux) import extraLinux;
else version (OSX) import extraOSX;
... and so on ...
```
Personally, I like to make the core code version-independent and OS-independent
and hide the variances in separate modules. Isn't foo() clean looking?
More information about the Digitalmars-d
mailing list