How to write a singleton template?
Kyle Furlong
kylefurlong at gmail.com
Sun Mar 19 16:19:49 PST 2006
Bruno Medeiros wrote:
> 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.
>
It is misleading because it asserts "Templates cannot be used to add non-static members or functions to classes." Even with the
example, its still a blanket, general statement. It should specify that the example is the only case which has the limitation.
More information about the Digitalmars-d
mailing list