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

Jacob Carlborg doob at me.com
Wed Mar 30 23:52:15 PDT 2011


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
}

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

auto foo = new Foo;

foo.bar; // works
foo.bar = 3; // currently does not work, bug
foo.bar(3); // works

-- 
/Jacob Carlborg


More information about the Digitalmars-d-learn mailing list