storing pointers in Variants

Ali Çehreli via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Sat Apr 26 17:48:52 PDT 2014


On 04/26/2014 04:08 PM, Matt wrote:
> I am trying to create a class that can do the following:
>
> ---
>
> int sample = 42;
>
> // myObj is an instance of the class I'm writing
> myObj.attach ("othername", sample);
>
> myObj.set ("othername", 69);
>
> writeln (myObj.get ("othername"), "\t", sample); // should produce '69  69'
>
> ---
>
> Currently, my class appends to an array of Variants, and can store data
> internally in this array. Ref parameters don't work with variants, and
> pointers cause exceptions to be thrown. What would be the best way to go
> about this?
>
> I had momentarily considered using a struct that stores a void pointer
> to the data, along with type info, and using this to replace the
> Variant, but I like the ability to change the type at runtime.
>
> Any advice would be much appreciated.

I think the following is a start:

import std.variant;

class MyClass
{
     Variant[string] store;

     void attach(T)(string key, ref T var)
     {
         store[key] = &var;
     }

     void set(T)(string key, T value)
     {
         *store[key].get!(T*) = value;
     }

     T get(T)(string key)
     {
         return *store[key].get!(T*)();
     }
}

void main()
{
     int sample = 42;

     auto myObj = new MyClass;
     myObj.attach("othername", sample);
     myObj.set("othername", 69);

     assert(myObj.get!int("othername") == 69);
     assert(sample == 69);
}

Ali



More information about the Digitalmars-d-learn mailing list