Class templates with types determined at runtime

Daniel Keep daniel.keep.lists at gmail.com
Tue Apr 7 21:07:36 PDT 2009


The major problem with this is that you're trying to get into a
situation where you don't know the type of T at compile-time, and you
CANNOT do that.

For example, your newContainer function can't return a "Container"
because "Container" isn't a concrete type; it's just a template.

The only thing I can think of that might help you is std.boxer (or
tango.core.Variant).  Variants and boxes can be passed around however
you'd like so long as you don't try to look inside.

As soon as you look inside, you need to have code specialised for each
supported type.

Something like this:

-----
import std.stdio;
import std.math;
import std.boxer;

void dostuff(Box cont)
{
    if( unboxable!(float)(cont) )
        writefln("%.12f", unbox!(float)(cont));

    else if( unboxable!(double)(cont) )
        writefln("%.12f", unbox!(double)(cont));
}

int main(string[] args)
{
    string precision = "double";
    if (args.length > 1 && args[1] == "single")
        precision = "single";

    auto cont = newContainer(precision);
    dostuff(cont);

    return 0;
}

Box newContainer(string precision)
{
    switch (precision)
    {
        case "single":
            return box( cast(float) PI );
        case "double":
            return box( cast(double) PI );
        default:
            /+
            // exit?  Eurgh!
            writefln("Error: unknown type '%s'.", precision);
            exit(1);
            +/
            throw new Exception("unknown type " ~ precision);
    }
}
-----

Hope that helps.

  -- Daniel



More information about the Digitalmars-d-learn mailing list