How to write a singleton template?
Kyle Furlong
kylefurlong at gmail.com
Wed Mar 15 00:34:25 PST 2006
Li Jie wrote:
> In article <dv8anc$2109$1 at digitaldaemon.com>, Kyle Furlong says...
>> 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);
>> }
>>
>> Or with inheritance:
>>
>> // Note here that there is some syntactic sugar for templated classes
>>
>> class Singleton(T)
>> {
>> static this()
>> {
>> _instance = new T();
>> }
>> public static T instance ()
>> {
>> return _instance;
>> }
>> protected static T _instance;
>> }
>>
>> class OnlyOne : Singleton!(OnlyOne)
>> {
>> private this() {}
>> }
>
> Thanks.
>
> In the version 2, must 'Singleton' template class and 'OnlyOne' class be in the
> same file?
>
No, D templates can be in separate modules, just import the module you put the template in.
> I've never seen the usage of 'class XXX(T)', I read 'class.html' and
> 'template.html', but not found. Which document mention it?
>
>
> - Li Jie
>
>
Its in http://www.digitalmars.com/d/template.html, about 80% down the page, with the heading Class Templates. What is
undocumented is the fact that struct templates are also legal. (a very nice feature IMHO)
More information about the Digitalmars-d
mailing list