How to write a singleton template?

Kyle Furlong kylefurlong at gmail.com
Wed Mar 15 16:01:48 PST 2006


Bruno Medeiros wrote:
> 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/
> 
> 

The documentation leads one to believe that this is impossible. Look under the limitations header. This needs to be clarified.



More information about the Digitalmars-d mailing list