Using opDispatch as *magic* getter/setter. Possible or not?

Steven Schveighoffer schveiguy at yahoo.com
Thu Mar 31 04:30:11 PDT 2011


On Thu, 31 Mar 2011 02:52:15 -0400, Jacob Carlborg <doob at me.com> wrote:

> On 3/31/11 2:32 AM, Aleksandar Ružičić wrote:
>> Is it possible to use opDispatch as generic getter and setter at the
>> same time? Something like __get() and __set() in PHP..
>>
>> this is what I've tried: https://gist.github.com/895571
>>
>> and I get Error: template instance opDispatch!("bar") matches more
>> than one template declaration, path\to\test.d(57):opDispatch(string
>> entryName) and path\to\test.d(66):opDispatch(string entryName)
>>
>> Is mixing @property with opDispatch supposed to work at all or is
>> opDispatch only ment for method calls?
>>
>> Or maybe there is some other way to achive what I want and I'm not
>> aware of it? :-)
>
> You can't have two methods named opDispatch like that. You can do  
> something like this:
>
> class Foo {
>
> @property ref ConfigSection opDispatch(string sectionName, Args  
> ...)(Args args)
> {
>      static if (Args.length == 0) {} // getter
>      else static if (Args.length == 1) { auto value = args[0]; } //  
> setter
> }

The issue is that you can't have two templates with the same exact  
template parameters, even if they have different function parameters.   
This is because the compiler first instantiates the template, then calls  
the function.

I hope this restriction can be lifted for the special case of template  
functions.  The ability to overload template functions is long overdue,  
especially when you are overloading with normal functions.

> Or, I think this will work as well:
>
> @property ref ConfigSection opDispatch(string sectionName, Args  
> ...)(Args args) if (Args.length == 0)
> {
> // getter
> }
>
>
> @property ref ConfigSection opDispatch(string sectionName, Args  
> ...)(Args args) if (Args.length == 1)
> {
> // setter
> }
> }

or you can change the template parameters in the opDispatch setter:

@property ref ConfigSection opDispatch(string sectionName, T : string)(T  
arg)

-Steve


More information about the Digitalmars-d-learn mailing list