Frage

How do I check whether a variable exists, i.e. is already declared in D?

The background is that I want to use version conditions but still have a default value:

version(A)
{
  immutable int var = 1;
}
version(B)
{
  immutable int var = 2;
}
// this is pseudo code
if (var is not yet declared)
{
  immutable int var = 3;
}

I just assume that this is possible in D as it has so much introspection...

War es hilfreich?

Lösung

Well, given what your use case appears to be, you're going about it incorrectly. You really should do something more like

version(A)
{
    immutable int var = 1;
}
else version(B)
{
    immutable int var = 2;
}
else
{
    immutable int var = 3;
}

But in the general case, if you're looking specifically to test whether a symbol exists, use is(typeof(symbol)) where symbol is the name of the symbol that you're testing for. So, if you wanted to test whether the variable var existed, you would do something like

static if(is(typeof(var)))
{
    //var exists
}

and of course to test that it doesn't exist, you just negate the condition:

static if(!is(typeof(var)))
{
    //var does not exist
}

typeof(exp) gets the type of an expression, and if the expression is invalid (because of a variable which doesn't exist or a function in the expression doesn't work with those arguments or whatever), then the result is void. is(type) checks whether the type is non-void. So, is(typeof(exp)) tests whether exp is a valid expression, and in the case where it's just a symbol name, that means that it's testing whether it's a valid symbol or not.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top