Implicit enum conversions are a stupid PITA

Adam D. Ruppe destructionator at gmail.com
Thu Mar 25 13:57:00 PDT 2010


On Thu, Mar 25, 2010 at 03:37:52PM -0500, Andrei Alexandrescu wrote:
> Contest: define "octal" as per the blueprint above and paste it here.

Trivial. I'll start with the code you posted on the bugzilla.

=====

template octal(string s)
{
    static assert(s.length > 0);
    static assert(s[0] >= '0' && s[0] < '8',
        "Incorrect character in octal constant: `" ~ s[0] ~ "'");
    static if (s.length == 1)
    {
        enum uint octal = s[0] - '0';
    }
    else
    {
        enum uint octal = 8 * (s[0] - '0') + octal!(s[1 .. $]);
    }
}

======

Then add just this:

====

import std.metastrings;

template octal(uint s) {
	enum uint octal = octal!(toStringNow!(s));
}

=====

Take the unittest from bugzilla and add the same using the literal:

unittest
{
    static assert(octal!"45" == 37);
    static assert(octal!"0" == 0);
    static assert(octal!"7" == 7);
    static assert(octal!"10" == 8);

    static assert(octal!45 == 37);
    static assert(octal!0 == 0);
    static assert(octal!7 == 7);
    static assert(octal!10 == 8);
}

void main() {}

Run it. Boom! The tests pass. Change the names to your heart's desire.


-- 
Adam D. Ruppe
http://arsdnet.net



More information about the Digitalmars-d mailing list