How to write a singleton template?
Bruno Medeiros
daiphoenixNO at SPAMlycos.com
Sun Mar 19 02:23:55 PST 2006
Kyle Furlong wrote:
> 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.
The limitations section is about instantiating templates that are
defined inside a class, it is not about mixing in in a template inside a
class, which is a different thing. The limitation exists only in the
first case. This behaviour make sense.
--
Bruno Medeiros - CS/E student
http://www.prowiki.org/wiki4d/wiki.cgi?BrunoMedeiros#D
More information about the Digitalmars-d
mailing list