storing pointers in Variants

Matt via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Sun Apr 27 18:17:33 PDT 2014


On Sunday, 27 April 2014 at 00:48:53 UTC, Ali Çehreli wrote:
>
> 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


Much obliged. Just working on preventing type errors, now. I'll 
let you know how it goes


More information about the Digitalmars-d-learn mailing list