Creating Structs/Classes at runtime?
Ali Çehreli
acehreli at yahoo.com
Mon Feb 18 17:09:06 PST 2013
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
More information about the Digitalmars-d-learn
mailing list