How to write a singleton template?

Li Jie cpunion at gmail.com
Wed Mar 15 00:28:04 PST 2006


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?

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





More information about the Digitalmars-d mailing list