Summary: Safe enum conversion
           Product: D
           Version: D2
          Platform: All
        OS/Version: All
            Status: NEW
          Severity: enhancement
          Priority: P2
         Component: Phobos

--- Comment #0 from 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!(Foo).to!(int) error

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:
------- You are receiving this mail because: -------

Reply via email to