Subtyping of an enum
XavierAP
n3minis-git at yahoo.es
Mon Apr 15 10:06:30 UTC 2019
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.
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?
You obviously need to re-think your problem and your design :)
> 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
More information about the Digitalmars-d-learn
mailing list