Implicit enum conversions are a stupid PITA

Adam D. Ruppe destructionator at gmail.com
Thu Mar 25 14:13:45 PDT 2010


On Thu, Mar 25, 2010 at 04:57:00PM -0400, Adam D. Ruppe wrote:
> Run it. Boom! The tests pass.

I always post too soon!

It fails with larger numbers. The octal!(string) code is to blame; it doesn't
raise 8 to the right power on strings with length > 2.

And opPow doesn't seem to work here. So I'll do it slightly differently:

====
/* new function */
uint octal(string num)() {
    static assert(num.length > 0);

    uint pow = 1;
    uint value = 0;

    for(int pos = num.length - 1; pos >= 0; pos--) {
        char s = num[pos];
        assert(s >= '0' && s < '8',
            "Incorrect character in octal constant: `" ~ s ~ "'");
	
	value += pow * (s - '0');
	pow *= 8;
  }

  return value;
}
/* end changes */

import std.metastrings;

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

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() {
	// a triple check
	pragma(msg, octal!666); // prints correctly as it compiles, yay

}
===

And as a final check:
        pragma(msg, octal!6668);
octal.d(9): Error: "Incorrect character in octal constant: `8'"
octal.d(22): Error: cannot evaluate octal() at compile time
octal.d(22): Error: cannot evaluate octal() at compile time
octal.d(43): Error: template instance octal.octal!(6668) error instantiating

Good, good. But is it still compile time elsewhere?

        writeln(octal!6668);

Same spewing errors. A bit wordy, but definitely gives error correctly.


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



More information about the Digitalmars-d mailing list