immutable singleton pattern with static opCall

Steven Schveighoffer schveiguy at yahoo.com
Mon Jun 28 05:58:31 PDT 2010


On Mon, 28 Jun 2010 08:40:36 -0400, Justin Johansson <no at spam.com> wrote:

> Steven Schveighoffer wrote:
>> On Mon, 28 Jun 2010 08:07:40 -0400, Justin Johansson <no at spam.com>  
>> wrote:
>>
>>> Steven Schveighoffer wrote:
>> 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());
> }

That's because toString should be a const function.

See http://d.puremagic.com/issues/show_bug.cgi?id=1824

please vote for the bug.

-Steve


More information about the Digitalmars-d mailing list