Static opDispatch
Steven Schveighoffer
schveiguy at yahoo.com
Sat Oct 1 16:50:47 PDT 2011
On Sat, 01 Oct 2011 12:34:50 -0400, Jacob Carlborg <doob at me.com> wrote:
> Have a look at the following code:
>
> class Foo
> {
> static Foo instance_;
>
> static Foo instance ()
> {
> if (instance_)
> return instance_;
>
> return instance_ = new Foo;
> }
>
> static auto opDispatch (string name, Args...) (Args args)
> {
> mixin("return instance." ~ name ~ "(args);");
> }
>
> void bar () {}
> }
>
> void main ()
> {
> Foo.bar;
> }
>
> Compiling the above code results in:
>
> Error: need 'this' to access member bar
>
> Is it possible somehow to make the above code compile?
It's an issue with namespace polution. Both instances and the type share
the same namespace. It's really a bad limitation IMO. I have a bug
report that helps try and separate it:
http://d.puremagic.com/issues/show_bug.cgi?id=6579
It should work if you use a different class as the singleton:
class Foo2
{
void bar () {}
}
class Foo
{
static Foo2 instance_;
static Foo2 instance ()
{
if (instance_)
return instance_;
return instance_ = new Foo;
}
static auto opDispatch (string name, Args...) (Args args)
{
mixin("return instance." ~ name ~ "(args);");
}
}
-Steve
More information about the Digitalmars-d
mailing list