Singletons, alias this and DMD crashing
Leandro Motta Barros
lmb at stackedboxes.org
Thu May 9 06:07:28 PDT 2013
Thanks for the comment! I noticed this wouldn't compile, though I
haven't really wondered why so. My email was more about the compiler
bug than about using alias this with singletons.
Anyway, while trying to circumvent the compiler bug, I did this:
import std.stdio;
class SImpl
{
void foo()
{
writeln("foo!");
}
private this() { }
}
class S
{
static @property SImpl instance()
{
if (_i is null)
_i = new SImpl();
return _i;
}
static SImpl _i;
alias instance this;
}
void main()
{
S.foo();
}
This works and compiles with DMD 2.062. (I don't like to have
to write this additional code manually, but I'll try to make something
about it :-) )
LMB
On Thu, May 9, 2013 at 7:04 AM, Jacob Carlborg <doob at me.com> wrote:
> On 2013-05-09 11:48, Jacob Carlborg wrote:
>
>> This won't work. You need to be able to overload on static, which you
>> can't. I've tried this with opDispatch.
>
>
> To elaborate. Below is your original with the "foo" method added.
>
>
> class S
> {
> static @property S instance()
> {
> if (_i is null) // #1
> _i = new S();
>
> return _i;
> }
>
> static S _i;
>
> alias instance this; // #2
>
> void foo () {}
> }
>
> If you try to call it like this: S.foo(), the compiler will complain that
> "foo" need access to "this". The "alias this" won't kick in.
>
> --
> /Jacob Carlborg
More information about the Digitalmars-d
mailing list