Two other kinds of static
bearophile
bearophileHUGS at lycos.com
Sat Jun 4 06:36:28 PDT 2011
Time ago I have half-seriously suggested a "static static", to solve a small problem I've has in my code. foo is a function template, so even if bar is static, every instantiation of foo gets a different bar:
auto foo(T)(int x) {
static bar = ...;
...
}
A "static static" means there is only one bar shared for all instances of foo, this is something I have desired a bit to do:
auto foo(T)(int x) {
static static bar = ...;
...
}
Now I have found a bit of need for another kind of static :-) In C/C++ there isn't this need because they don't have nest functions as D (GCC supports nest functions, but they are not used much). An example:
int foo() {
int bar() {
static(foo) int[10] spam;
//...
}
// ...
}
That means something like:
int foo() {
int[10] spam;
// spam not visible here
int bar() {
// use spam here only
}
// spam not visible here
}
"spam" is static regarding the bar() function, but it's not static (so it's automatic) for foo() function. This is sometimes useful because I know how bar will be called (inside foo), but I don't know how foo() itself will be called and used, and generally foo() may be a recursive function. So this is wrong code, I can't set spam as a truly static variable:
int foo() { // recursive
int bar() { // not recursive
static int[10] spam; // wrong
// ...
}
return bar() + foo();
}
Bye,
bearophile
More information about the Digitalmars-d
mailing list