Static opDispatch

Martin Nowak dawg at dawgfoto.de
Sun Oct 2 08:13:45 PDT 2011


On Sun, 02 Oct 2011 10:38:44 +0200, Jacob Carlborg <doob at me.com> wrote:

> 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.
>

Changing this would invert the name lookup priority of opDispatch.
What you request makes Foo.bar inaccessible, i.e. you can't take the  
address of it any longer.

martin


More information about the Digitalmars-d mailing list