The following declaration implements the classic singleton
design pattern and uses D's static opCall feature to make
for brevity of use, that is to say, you can access the singleton
instance by simply writing Foo() rather than Foo.instance.

Furthermore, the use of private on the static instance forces
use of the function call style idiom, i.e. Foo(), rather than
the long hand form Foo.instance.

class Foo
{
   static private Foo instance;

   static this() {
      instance = new Foo;
   }

   static Foo opCall() {
      return instance;
   }
}


Now I would like to make this class immutable.  How many times
should I have to type the immutable keyword to achieve this result?

Ideally once only would be my answer.  But the following, possibly naive
code, does not compile:

immutable class Foo
{
   static private Foo instance;

   static this() {                      // line 9
      instance = new Foo;
   }

   static Foo opCall() {                // line 13
      return instance;
   }
}

test.d(9): Error: function test.Foo._staticCtor2 without 'this' cannot be const/immutable test.d(13): Error: function test.Foo.opCall without 'this' cannot be const/immutable

How should this declaration best be written to achieve my design?  One
variation I have is as follows but it is very noisy with the immutable
keyword.

class Foo
{
   static private immutable Foo instance;

   static this() {
      instance = cast(immutable Foo) new Foo;
   }

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


Reply via email to