Subtyping of an enum

diniz diniz at posteo.net
Mon Apr 15 14:11:05 UTC 2019


Le 15/04/2019 à 10:39, Anton Fediushin via Digitalmars-d-learn a écrit :
> This seems to work just fine for assigning and comparisons but passing Enum as a 
> function argument does not work:
> ```
> void fun(Enum e) {}
> 
> fun(Enum.foo);
> ---
> Error: function fun(Enum e) is not callable using argument types (internal)
> Cannot pass argument foo of type internal to parameter Enum e.
> ```

I don't understand why you just don't call fun with an Enum (struct) param, 
since that is how fun is defined. This works by me (see call in main):

struct Enum {
   private {
     enum internal {
       foo,
       bar
     }
     internal m_enum;
   }
   this (internal i) { m_enum = i; }
   alias m_enum this;
   string toString() {
     switch (this.m_enum) {
         case internal.foo : return "FOO" ;
         case internal.bar : return "BAR" ;
         default : assert(0) ;
     }
   }
}

void fun (Enum e) {
     writeln(e) ;
}

void main() {
     auto e = Enum(Enum.foo) ;
     fun(e) ;	// -> "FOO"
}

[And I wouldn't make the enum (little e) private, this just risks complicating 
code, also eg in testing, I would just not export it.]

-- 
diniz {la vita e estranj}


More information about the Digitalmars-d-learn mailing list