digitalmars.D - "static static" again
- bearophile (34/34) Aug 21 2011 A not too much serious post fit for a slow Sunday :-)
A not too much serious post fit for a slow Sunday :-) Time ago I have half-seriously suggested the "static static", to be used to define a static variable that is static (shared) for all instantiations of one function template. With it you avoid a global variable, and you have the advantages of a static variable: auto foo(T)(T x) { static static int n = 0; n++; return x * n; } I have found another use case for static static :-) You know this idiom, a helper function that helps the instantiation of a struct template (sometimes the static struct Foo is defined inside foo): struct Foo(T) { T x; } Foo!U foo(U)(U x_) { return Foo!U(x_); } void main() { Foo!int f1 = foo(1); Foo!double f2 = foo(1.5); } If opCall is static static, then I think you are allowed to write: struct Foo(T) { T x; static static Foo!U opCall(U)(U x_) { return Foo!U(x_); } } void main() { Foo!int f1 = Foo(1); Foo!double f2 = Foo(1.5); } You have just one name (not foo and Foo), and Foo is a global (template) name (it's not hidden inside foo). And I like it being a single piece, instead of two. The body of static static member functions doesn't get copied for each template instantiation, this helps reduce template bloat a bit. Bye, bearophile
Aug 21 2011