On Sunday, February 24, 2013 04:33:29 Martin wrote:
>       import std.stdio;
> 
>       class TestClass(T)
>       {
>       private:
>               __gshared TestClass[] globalInstances;
>       public:
>               this()
>               {
>                       globalInstances ~= this;
>               }
> 
>               void test()
>               {
>                       writeln("Address of variable globalInstances is: 0x",
> globalInstances.ptr);
>               }
> 
>       }
> 
>       void main(string[] args)
>       {
> 
>               TestClass!(int) t1 = new TestClass!(int);
>               TestClass!(string) t2 = new TestClass!(string);
> 
>               t1.test;
>               t2.test;
> 
>               readln;
> 
>       }
> 
> Outputs:
> Address of variable globalInstances is: 0x4F3F80
> Address of variable globalInstances is: 0x4F3F60
> 
> Which I guess makes sense since there's seperate globalInstances
> variables generated per template instance of the class. I want to
> store ALL instances, no matter if it's a TestClass!(int) or
> TestClass!(string) though.
> 
> Should I just use a __gshared void*[] globalInstances outside of
> the template and cast when necessary or is there an easier way
> that I'm too stupid to see? It's really late here...

Every instance of a template is a completely different type than every other 
instance. They have no more relation to each other than

class Foo {}

and

class Bar {}

do. Remember that when you're instantiating a template, your literally 
generating code. It's basically a lot of copying and pasting by the compiler. 
If you want to store something for all instantiaties of a template, then it's 
going to need to be done outside of the template. However, I'd point out that 
in general, keeping track of every instance of a class isn't a good idea, and 
treating each instantiation of a template as if it had a relation to other 
instantiations of a template is also generally a bad idea. You may indeed have 
a use case where it makes sense, but my first inclination would be to suggest 
that you rethink whatever you're doing.

- Jonathan M Davis

Reply via email to