www.digitalmars.com         C & C++   DMDScript  

digitalmars.D - maybe it's a bug

reply Kostya Lisiy <Kostya_member pathlink.com> writes:
In my program I have several classes which I would like to use as singletons

And I made this little template:

<code>
template Singleton(T)
{
public static this(){ m_instance = new T(); }
public static T get(){ return m_instance; }
private static T m_instance;
private this(){}
}
// and this is how it's used:
class Foo
{
mixin Singleton!(Foo);
}
</code>
The following compile error occured:
<i>test.d(23): class test.Foo test.Foo.Singleton!(...) Singleton_C4test3Foo.this
is private</i>

While the next code works perfectly:
<code>
template Singleton(T)
{
public static this(){ m_instance = new T(); }
public static T get(){ return m_instance; }
private static T m_instance;
private this(){}
}
class Foo
{
mixin Singleton!(Foo);
private this(){} // <- only this added
}
</code>
So both mixin and class kind of define the same private constructor twice.
This is strange. If asked, I would rather think that the first code sample would
compile and the second would not.
Oct 02 2005
parent Chris Sauls <ibisbasenji gmail.com> writes:
I've done singletons in D, using two different methods.  I've done the mixin
style you're 
attempting, and had similar issues, although the biggest one is that, if you
use this 
method, then you can't really do anything in your constructor.  Ew.  The second
method, 
which has become my personal preference, is to use what I like to call the
"static 
abstract" trick.  Example:

# public abstract class MySingleton : Object { static:
#   static this () { // I explify 'static' just to be sure
#   }
#
#   public int method () {
#     return 0;
#   }
#
#   public int field;
# }
#
# void main () {
#   MySingleton.method();
# }

The only potential downside (AFAIK) is that you can't store references to the
singleton. 
You have to refer to it by name.  Maybe D could have a "static class reference" 
type/subtype/ability for cases like this.

-- Chris Sauls
Oct 02 2005