[Issue 8143] New: Safe std.conv.to enum conversion

d-bugmail at puremagic.com d-bugmail at puremagic.com
Thu May 24 14:44:51 PDT 2012


http://d.puremagic.com/issues/show_bug.cgi?id=8143

           Summary: Safe std.conv.to enum conversion
           Product: D
           Version: D2
          Platform: All
        OS/Version: All
            Status: NEW
          Severity: enhancement
          Priority: P2
         Component: Phobos
        AssignedTo: nobody at puremagic.com
        ReportedBy: bearophile_hugs at eml.cc


--- Comment #0 from bearophile_hugs at eml.cc 2012-05-24 14:46:34 PDT ---
import std.conv: to;
enum Foo : int { A = 10, B = 20 }
void main() {
    int x = 10;
    Foo f1 = to!Foo(x);
    assert(f1 == Foo.A);
    x = 5;
    Foo f2 = to!Foo(x); // needs to throw an exception
}


DMD 2.060alpha gives:

...\dmd2\src\phobos\std\conv.d(267): Error: template std.conv.toImpl does not
match any function template declaration
...\dmd2\src\phobos\std\conv.d(298): Error: template std.conv.toImpl cannot
deduce template function from argument types !(Foo)(int)
...\dmd2\src\phobos\std\conv.d(267): Error: template instance toImpl!(Foo)
errors instantiating template
temp.d(5): Error: template instance std.conv.to!(Foo).to!(int) error
instantiating


This is handy to *safely* convert run-time values to enum items. Using a
cast(Foo) is useful in other cases, because cast(Foo) doesn't raise a run-time
exceptions. The same difference is visible in this program:


import std.conv: to;
void main() {
    int x = -10;
    uint y1 = cast(uint)x; // no errors here
    uint y2 = to!uint(x); // throws std.conv.ConvOverflowException
}

-- 
Configure issuemail: http://d.puremagic.com/issues/userprefs.cgi?tab=email
------- You are receiving this mail because: -------


More information about the Digitalmars-d-bugs mailing list