On Sat, 04 Jun 2011 09:36:28 -0400, bearophile <[email protected]> wrote:

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 = ...;
    ...
}

Just put it outside foo:

private static bar = ...;

auto foo(T)(int x) {
   ...
}



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() {
   static int[10] spam;
   int bar() {
   }
}

I understand you want to limit the accessible namespace, but saying "it can't be done" is not true. It can be done, with proper control over the code. That is, as long as you follow your own rules, outsiders can't break into it. I'd recommend naming the variables in a way that "suggests" the namespace they should be in:

int foo() {
   static int[10] bar_spam; // only used inside bar
   int bar() {
   }
}

-Steve

Reply via email to