How to write a singleton template?
Kyle Furlong
kylefurlong at gmail.com
Tue Mar 14 22:03:27 PST 2006
Li Jie wrote:
> I try to write a singleton template, but has not succeeded:
>
> A:
> template Singleton(T)
> {
> private T _instance;
>
> static this()
> {
> _instance = new T();
> }
>
> public T instance ()
> {
> return _instance;
> }
> }
>
> B:
> template Singleton(T)
> {
> class Singleton
> {
> private static T _instance;
>
> static this()
> {
> _instance = new T();
> }
>
> public static T instance ()
> {
> return _instance;
> }
> }
> }
>
> C:
> template Singleton(T)
> {
> class Singleton
> {
> private static T _instance = null;
>
> public static T instance ()
> {
> if (_instance == null)
> _instance = new T();
> return _instance;
> }
> }
> }
>
>
> // use it:
>
> class AAA
> {
> public void hello ()
> {
> printf("hello\n");
> }
> }
>
> int main(char[][] args)
> {
> alias Singleton!(AAA) aaa;
> aaa.instance().hello(); // <== Segment fault !!!!!
>
> return 0;
> }
>
> I want to know, how to write a singleton template?
>
>
>
> Thanks.
>
> - Li Jie
>
>
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() {}
}
More information about the Digitalmars-d
mailing list