[Issue 10814] New: Formatting string-based enum prints its name instead of its value
d-bugmail at puremagic.com
d-bugmail at puremagic.com
Tue Aug 13 02:17:04 PDT 2013
http://d.puremagic.com/issues/show_bug.cgi?id=10814
Summary: Formatting string-based enum prints its name instead
of its value
Product: D
Version: D2
Platform: All
OS/Version: All
Status: NEW
Severity: normal
Priority: P2
Component: Phobos
AssignedTo: nobody at puremagic.com
ReportedBy: andrej.mitrovich at gmail.com
--- Comment #0 from Andrej Mitrovic <andrej.mitrovich at gmail.com> 2013-08-13 02:17:00 PDT ---
-----
import std.stdio;
enum Type : string
{
button = "type::button",
}
void main()
{
writeln(Type.button);
writefln("%s", Type.button);
writeln(cast(string)Type.button);
}
-----
Prints:
button
button
type::button
It's really strange that we have to cast an enum just to retrieve the actual
value.
Note for example what happens when you use '%d' on an enum:
-----
import std.stdio;
enum Type : int
{
button = 1,
}
void main()
{
writefln("%s", Type.button);
writefln("%d", Type.button);
}
-----
Prints:
button
1
However you can't use this trick for string enums since there's no equivalent
format specifier to retrieve an actual string.
There should be a way to always format the actual value of an enum in
writef/format calls. "%s" might try to do the convenient thing by default, so
maybe a new format specifier would be required? E.g. "%e" for enum values.
Alternatively one would write a helper template, e.g. toBaseValue(enumVal),
which would return the base type value of an enum:
-----
import std.stdio;
enum Type : int
{
button = 1,
}
enum Type2 : string
{
button = "ttk::button",
}
template EnumBaseType(E) if (is(E == enum))
{
static if (is(E B == enum))
alias EnumBaseType = B;
}
T toBaseType(E, T = EnumBaseType!E)(E val)
{
return cast(T)val;
}
void main()
{
writefln("%s %s", Type.button.toBaseType, Type2.button.toBaseType);
}
-----
Prints:
1 ttk::button
--
Configure issuemail: http://d.puremagic.com/issues/userprefs.cgi?tab=email
------- You are receiving this mail because: -------
More information about the Digitalmars-d-bugs
mailing list