Is it possible to store properties via opDispatch using tuples?

Jacob Carlborg doob at me.com
Thu Jan 16 23:56:18 PST 2014


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.

-- 
/Jacob Carlborg


More information about the Digitalmars-d-learn mailing list