Named Global Arrays
Tofu Ninja via Digitalmars-d
digitalmars-d at puremagic.com
Mon Aug 11 23:09:51 PDT 2014
This might already exist but I thought that it was cool that it
was possible in D non the less. Just thought I would share :)
struct namedGlobalArray(string name, T)
{
import std.typecons;
T opDispatch(string var)(T x)
{
Nullable!T tmp = x;
return accessStorage!var(tmp);
}
T opDispatch(string var)()
{
Nullable!T tmp;
return accessStorage!var(tmp);
}
public T accessStorage(string var)(Nullable!T x)
{
static T data;
if(!x.isNull) data = x;
return data;
}
}
Example usage...
Module A:
void main(string[] args)
{
import moduleB;
namedGlobalArray!("GlobArray",int) glob;
namedGlobalArray!("GlobArray2",int) glob2;
glob.a = 10;
glob.b = 20;
glob2.a = 77;
assert(glob.a == 10);
assert(glob.b == 20);
assert(glob.c == 0);
assert(glob2.a == 77);
testGlob();
assert(glob.a == 314);
assert(glob.b == 20);
assert(glob.c == 9);
assert(glob2.a == 77);
}
Module B:
public void testGlob()
{
namedGlobalArray!("GlobArray",int) glob;
glob.a = 314;
glob.c = 9;
}
There might be a way to do it without Nullable but I couldn't
think of one...
More information about the Digitalmars-d
mailing list