How to write a singleton template?

Bruno Medeiros daiphoenixNO at SPAMlycos.com
Wed Mar 15 13:40:52 PST 2006


Kyle Furlong wrote:
> 
> You might want to consider a mixin:
> 
> template Singleton(T)
> {
>     static this()
>     {
>         _instance = new T();
>     }
>     public static T instance ()
>     {
>         return _instance;
>     }
>     private static T _instance;
> }
> 
> class OnlyOne
> {
>     // Can't include this in the mixin,
>     // because D can only mixin static things to classes
>     private this() {}
>     mixin Singleton!(OnlyOne);
> }
> 

"because D can only mixin static things to classes"
-> That is incorrect, you can include instance methods and constructors 
just fine. See for yourself in a example such as this:

   template Baz() {
     public void func() { writefln(x); }
     public this() { writefln("Construct!"); }
   }

   class Foo {
     int x = 2;
     mixin Baz!();
   }
...
   (new Foo).func();


The only problem is with private protection attributes and constructors, 
as reported in bug:
news://news.digitalmars.com:119/bug-49-3@http.d.puremagic.com/bugzilla/


-- 
Bruno Medeiros - CS/E student
http://www.prowiki.org/wiki4d/wiki.cgi?BrunoMedeiros#D



More information about the Digitalmars-d mailing list