Subtyping of an enum

Anton Fediushin fediushin.anton at yandex.com
Mon Apr 15 10:34:42 UTC 2019


On Monday, 15 April 2019 at 10:06:30 UTC, XavierAP wrote:
> On Monday, 15 April 2019 at 08:39:24 UTC, Anton Fediushin wrote:
>>
>> Hello! I am currently trying to add a custom `toString` method
>
> Several remarks... First of all, strings can be compared 
> (alphabetically) as well as integers, e.g.
> assert("foo" > "bar")
> Perhaps not your use case, but worth noting.

I already know that but defining enum with strings would break my 
code:
```
assert(Enum.foo < Enum.bar);
```
Would never succeed.

>
> You have defined your sub-typing the opposite way that you 
> wanted it to work: every `Enum` is an `internal`, but the other 
> way around an `internal` may not work as an `Enum`. Your `fun` 
> would in principle work if it were defined with an `internal` 
> but passed an `Enum`... Of course you have defined `internal` 
> as nested private so no... But then how did you want anything 
> to work if no one outside Enum knows the super-type?

Isn't this how subtyping works for integers and other types? For 
example, you have subtyped an integer and added some new methods 
to it?

>
> You obviously need to re-think your problem and your design :)

The problem here is that I want to keep methods that are related 
to an enum inside of this enum for purely aesthetic and 
organizational purposes.

>
>> Obvious solution is to wrap an enum in a structure and utilize 
>> 'alias this' for subtyping like this:
>
> Actually the obvious solution (not sure if it otherwise works 
> for you) would be to take advantage of D's Uniform Function 
> Call Syntax [1] and define toString as a global function that 
> can be called as a method:
>
> enum Fubar { foo, bar }
>
> string toString(Fubar fb)
> {
> 	return "It works.";
> }
>
> void main()
> {
> 	import std.stdio;
> 	writeln(Fubar.foo.toString);
> }
>
> _________
> [1] 
> https://tour.dlang.org/tour/en/gems/uniform-function-call-syntax-ufcs

This is what I am doing now, I was just curious if there was a 
better solution. These global functions pollute global namespace. 
I know that I could put them into an own module and 'public 
import' just my enum because these methods would rarely be used 
by the other components of my application. If I would want to use 
them though, I'd have to import that ugly module and never forget 
to call `writeln(a.toString)` instead of `writeln(a)` or else 
it'll do not what I wanted.

And once more, what I want to achieve is purely about overall 
code organization. I mean, if structs (data) can have functions 
(methods) that are performed on them, why an enum (single value) 
cannot have own methods performed on it?




More information about the Digitalmars-d-learn mailing list