Idiom #108 Determine if variable name is defined
Print the value of variable x, but only if x has been declared in this program.
This makes sense in some languages, not all of them. (Null values are not the point, rather the very existence of the variable.)
int x = 42;
void printIfDefined(alias name)()
{
import std.stdio: writeln;
static if( __traits(compiles, writeln(mixin(name))))
writeln(mixin(name));
}
void main(string[] args)
{
printIfDefined!"x";
printIfDefined!"Foo.bar";
}
The string is turned into its equivalent as an identifier using a mixin then we statically check if the code that displays the variable will be compiled. If so then write the variable for real.
In D this doesn't makes much sense since everything in this function is prepared at compile-time.
In D this doesn't makes much sense since everything in this function is prepared at compile-time.