Static opDispatch

Jacob Carlborg doob at me.com
Sun Oct 2 01:38:44 PDT 2011


On 2011-10-02 01:50, Steven Schveighoffer wrote:
> 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

This limitation starts to get annoying, but thanks for the workaround.

-- 
/Jacob Carlborg


More information about the Digitalmars-d mailing list