operator overload for enum

Timon Gehr via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Fri Jun 10 04:38:13 PDT 2016


On 10.06.2016 13:02, Satoshi wrote:
> Hello,
> why operator overloading is not working as a static methods through the
> UFCS?
> ...

It's an arbitrary limitation.
https://issues.dlang.org/show_bug.cgi?id=8062

(The specification has been updated in the meantime, it now documents 
the limitation explicitly. https://dlang.org/spec/operatoroverloading.html)

> I need overload a << operator in this way:
>
> enum PlatformID {
>      None,
>      Trinix,
>      Unix,
>      MacOS,
>      Windows
> }
>
> PlatformID toPlatformID(string platform) {
>      switch (platform.toLower()) {
>          case "trinix":  return PlatformID.Trinix;
>          case "unix":    return PlatformID.Unix;
>          case "macos":   return PlatformID.MacOS;
>          case "windows": return PlatformID.Windows;
>          default:        return PlatformID.None;
>      }
> }
>
> void opBinary(string op)(ref PlatformID plat, auto ref const string str)
> if (op == "<<") {
>      plat = toPlatformID(str);
> }
>
>
> void thisIsTest() {
>      PlatformID id;
>      id << "x86_64"; // this is not working
>      id.opBinary!("<<")("test"); // but this works O.K.
>
> }

Yuck. This should at the very least be opAssign instead.


More information about the Digitalmars-d-learn mailing list