Widening a type

Doctor J nobody at nowhere.com
Thu Apr 16 19:11:00 PDT 2009


OK, here's one for you that sounds like it ought to be easy, but I don't immediately see how to do it in a pretty way.

Given a type parameter T of a template:
If T is an integral type, I want to declare a variable 'widest' of type ulong;
If T is a floating-point type, I want to declare a variable 'widest' of type double.
And it has to be prettier than my solution.  :)

        static if (is (T: ulong))
            ulong widest = 0;
        else if (is (T: double))
            double widest = 0.0;
        else
            static assert (false, "Unimplemented type " ~ T.stringof) ;

Now, I thought this sounds like a great job for a mixin:
 
template Widen (T, alias varname)
{
    static if (is (T: ulong))
        ulong varname = 0;
    else if (is (T: double))
        double varname = 0.0;
    else
        static assert (false, "Unimplemented type " ~ T.stringof) ;
}

mixin Widen!(T, widest);

...but alas, "Declaration expected, not 'if'".

Help?




More information about the Digitalmars-d-learn mailing list