February 19, 2013 Re: Creating Structs/Classes at runtime? | ||||
---|---|---|---|---|
| ||||
Posted in reply to Brian Brady | On 02/18/2013 04:31 PM, Brian Brady wrote: > So a program that reads in a csv of the form: > > "string, number, number, number" > > and stores it in a container/matrix/associative array > > could also read in > > "number, number, string, number, string, number, number, number" > > and store it in a container with similar properties. > Once I can get both csvs input in the same manner, I can work on > determining what is in each container, and go from there. How about an OO solution? import std.stdio; interface Data { void doSomething(); } // This works with any simple type class SimpleData(T) : Data { T value; this(T value) { this.value = value; } void doSomething() { writefln("Doing something with %s %s", T.stringof, value); } } alias IntData = SimpleData!int; alias StringData = SimpleData!string; // My special type struct MyStruct { double d; string s; void foo() { writefln("Inside MyStruct.foo"); } } // This works with my special type class MyStructData : Data { MyStruct value; this(double d, string s) { this.value = MyStruct(d, s); } void doSomething() { writefln("Doing something special with this MyStruct: %s", value); value.foo(); } } void main() { Data[] dataContainer; // Append according to what gets parsed from the input dataContainer ~= new IntData(42); dataContainer ~= new StringData("hello"); dataContainer ~= new MyStructData(1.5, "goodbye"); // Use the data according to the Data interface foreach (data; dataContainer) { data.doSomething(); } } The output: Doing something with int 42 Doing something with string hello Doing something special with this MyStruct: MyStruct(1.5, "goodbye") Inside MyStruct.foo Ali |
February 19, 2013 Re: Creating Structs/Classes at runtime? | ||||
---|---|---|---|---|
| ||||
Posted in reply to Ali Çehreli | On Tuesday, 19 February 2013 at 01:09:06 UTC, Ali Çehreli wrote:
[...]
> How about an OO solution?
That looks awesome. :)
I'll have a play with it and see if I can bend it to my will.
Thanks for the help.
Like I said, I'm a bit of a noob, so a push in a more suitable direction is always appreciated. :)
Regards
Brian
|
Copyright © 1999-2021 by the D Language Foundation