Overriding to!string on enum types
    monarch_dodra via Digitalmars-d-learn 
    digitalmars-d-learn at puremagic.com
       
    Tue Sep  2 08:42:35 PDT 2014
    
    
  
On Tuesday, 2 September 2014 at 14:59:41 UTC, evilrat wrote:
> sorry, i forgot everything.
> here is example of how to do this
> -----
>
> import std.conv : to;
>
> enum Test
> {
>  One,
>  Two,
>  Three,
> }
>
>
> template to(T: string)
> {
>  T to(A: Test)(A val)
>  {
>   final switch (val)
>   {
>    case Test.One: return "1";
>    case Test.Two: return "2";
>    case Test.Three: return "3";
>   }
>  }
> }
>
>
> void main()
> {
> assert(to!string(Test.One) == "1");
> auto t = cast(Test)2;
> assert(to!string(t) == "3");
> assert(to!int("4") == 4); // shows original to! template works
> }
Word of warning: You are not overriding "to", but rather, simply 
defining your own "to" locally, which resolves as a better match 
in the context where you are using it.
If you pass the enum to another function in another module, your 
"to" will NOT be called.
    
    
More information about the Digitalmars-d-learn
mailing list