How can I check if a variable is declared in D?

How to check if a variable exists i.e. already announced in D?

This assumes I want to use version conditions, but still have the default:

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'm just guessing it is possible in D as it has so much introspection ...

+3


source to share


1 answer


Ok, considering your use case seems like you are doing it wrong. 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 general, if you want to check if a symbol exists, use is(typeof(symbol))

, where symbol

is the name of the symbol you are testing for. So, if you wanted to check if a variable exists var

, you would do something like

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

      



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

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

      

typeof(exp)

gets the type of the expression, and if the expression is invalid (because of a variable that doesn't exist or the function in the expression doesn't work with those arguments or whatever), then the result void

. is(type)

checks if the type is not void

. So, it is(typeof(exp))

checks if exp is a valid expression, and in case it is just a symbol name, that means it checks if it is a valid symbol or not.

+10


source







All Articles