Widening a type

Daniel Keep daniel.keep.lists at gmail.com
Thu Apr 16 21:12:41 PDT 2009



Doctor J wrote:
> 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?

The error tells you everything you need to know if you read it.

Actually, you have two problems: you're trying to use "if" where you
should be using "static if", and you can't alias a symbol name then use
it in a declaration.  Here's a fixed, expanded version.

template Widen (T, char[] varname)
{
    static if (is (T: ulong))
    {
        mixin(`ulong `~varname~` = 0;`);
    }
    else
    {
        static if (is (T: double))
        {
            mixin(`double `~varname~` = 0.0`);
        }
        else
        {
            static assert (false, "Unimplmented type " ~ T.stringof);
        }
    }
}

You can remove those braces, I just wanted to point out that putting
"static" out the front of an "if" doesn't magically make the "else"
branch static as well.

  -- Daniel


More information about the Digitalmars-d-learn mailing list