digitalmars.D.learn - storing pointers in Variants
- Matt (18/18) Apr 26 2014 I am trying to create a class that can do the following:
- =?UTF-8?B?QWxpIMOHZWhyZWxp?= (29/45) Apr 26 2014 I think the following is a start:
- Matt (3/31) Apr 27 2014 Much obliged. Just working on preventing type errors, now. I'll
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.
Apr 26 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
Apr 26 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); } AliMuch obliged. Just working on preventing type errors, now. I'll let you know how it goes
Apr 27 2014