immutable singleton pattern with static opCall

Justin Johansson no at spam.com
Mon Jun 28 05:40:36 PDT 2010


Steven Schveighoffer wrote:
> On Mon, 28 Jun 2010 08:07:40 -0400, Justin Johansson <no at spam.com> wrote:
> 
>> Steven Schveighoffer wrote:
>>
>> btw. The reason I marked the static instance member as private
>> was simply to enforce stylist use of Foo() rather than Foo.instance
> 
> Yuck Foo().xyz :)
> 
> But, whatever floats your boat.

He he, that's a cute quip.

> To go one step further, if you want it to truly be a singleton type, you 
> should mark the constructor private.
> 
> -Steve

Indeed.  I forgot the private constructor in this version but had it
in earlier versions.

Continuing on with the saga, it's a pity that immutable
is not compatible with Object toString method without a cast.

class Foo
{
    static immutable private Foo instance;

    static this() {
       instance = new Foo;
    }

    static immutable(Foo) opCall() {
      return instance;
    }

immutable:
   private this() {}
}


void main()
{
    // numerous compile errors if the cast is left out
    stdout.writefln( "Foo() = %s", cast(Foo) Foo());
}

JJ


More information about the Digitalmars-d mailing list