RejectedSoftware Forums

Sign up

Using string enums in templates

I am attempting the following:

constants.d:

module constants;

enum Urls : string
{
    root = "/",
    awesome = root ~ "AwEsOmE"
}

template.dt:

//...
- import constants;
p= Urls.awesome
//...

The p element includes the string "awesome" after this, not "AwEsOmE".

Am I missing something or is this a bug? It works if I declare it as "enum urlAwesome = "..."" instead, but I don't get nesting then.

Re: Using string enums in templates

Also, I get linker errors if I declare the members as "immutable" instead of "enum". :/

Re: Using string enums in templates

After giving it some thought, it seems logical: getting the string of an enum via toString() will result in its (serialised) name, not its value. But how should I go about this in this case?

Re: Using string enums in templates

An easy way would be to use stringof:

std.stdio.writefln("url: %s", Urls.awesome.stringof);

You could probably use traits too.

Re: Using string enums in templates

Am 22.02.2013 20:15, schrieb Matej Nanut:

I am attempting the following:

constants.d:

module constants;

enum Urls : string
{
   root = "/",
   awesome = root ~ "AwEsOmE"
}

template.dt:

//...
- import constants;
p= Urls.awesome
//...

Since writefln("%s", Urls.awsome); also prints out "awesome", I think
the behavior inside of the templates is consistent and it should be,
whatever writefln or to!string() decide to do. But it's also logical
if you compare it to normal int-based enums - those are most certainly
expected to print their name instead of their integer value and making
an exception for string based enums would probably cause more confusion
in the end.

So I guess it comes down to two possibilities to stay as close to the
original code as possible:

p= cast(string)Urls.awesome

or this to keep the template code the same, but simulate the desired
nesting using a struct/class:

struct Urls {
	enum root = "/";
	enum awesome = root ~ "AwEsOmE";
}

Both not the prettiest thing in the world, but in the end I think it's
worth to keep stringification behavior across differently typed named
enums consistent.

Re: Using string enums in templates

I completely agree that behaviour should not be different here, I was really hoping for another way to do this neatly. I quite like the struct one, I don't think it's much worse than the original.

Thanks!