Is it possible to store properties via opDispatch using tuples?

H. S. Teoh hsteoh at quickfur.ath.cx
Fri Jan 17 07:55:02 PST 2014


On Fri, Jan 17, 2014 at 08:56:18AM +0100, Jacob Carlborg wrote:
> On 2014-01-16 21:26, Gary Willoughby wrote:
> >What i would like to achieve is to dynamically assign and retrieve
> >properties without declaring them first. For example:
> >
> >class T
> >{
> >     public this()
> >     {
> >         this.foo = "bar";
> >     }
> >}
> >
> >Ordinarily the above won't compile because 'foo' hasn't been declared
> >but with opDispatch i can handle this. The problem is how do i handle
> >different types of each property.
> >
> >I was thinking about something like this:
> >
> >class A
> >{
> >}
> >
> >class B : A
> >{
> >}
> >
> >class C : B
> >{
> >}
> >
> >class T
> >{
> >     private Tuple[string] _properties;
> >
> >     public this()
> >     {
> >         this.a = new A();
> >         this.b = new B();
> >         this.c = new C();
> >     }
> >
> >     public void opDispatch(string name, T)(T element)
> >     {
> >         this._properties[name] = Tuple(T, element);
> >     }
> >
> >     public auto opDispatch(string name)()
> >     {
> >         if (name in this._properties)
> >         {
> >             return
> >cast(this._properties[name][0])this._properties[name][1];
> >         }
> >     }
> >}
> >
> >Of course this doesn't compile but is this actually possible? i.e.
> >storing the type and data. Then on retrieval returning the correct data
> >cast to the correct type? All done dynamically without any property
> >being pre-declared.
> 
> I have no way of seeing this work. The problem is you need to
> somehow store the static type revived in opDispatch. But to store an
> unknown type as an instance variable you need to use a template
> class.
[...]

Couldn't you just return a Variant? I thought this is what Variants are
made for.


T

-- 
"The whole problem with the world is that fools and fanatics are always so certain of themselves, but wiser people so full of doubts." -- Bertrand Russell. "How come he didn't put 'I think' at the end of it?" -- Anonymous


More information about the Digitalmars-d-learn mailing list