Using "cast(enum)" for explicit request of ctfe
monarch_dodra
monarchdodra at gmail.com
Wed Dec 4 03:12:53 PST 2013
I love D's ctfe capabilities. They allow using complex values,
with no run-time cost, and at a very low "code" cost.
One thing that does kind of get on my nerves is how you *always*
have to declare an actual enum to do that. You can't do CTFE on
the fly.
This ranges from mildly annoying, typically:
//Declare a CTFE message
enum message = format("Some message: %s", some_static_args);
//Use the CTFE message
enforce(pointer, message);
Or, also,
enum fib5 = fib(5); //CTFE calculate
writeln(fib5); //use
To, sometimes, downright *impossible*. If you ever need to do
CTFE inside the body of a static foreach, dmd will block you due
to "redeclaration":
foreach(T; Types)
{
enum message = format("This type is %s.", T.stringof);
//Error! Redaclaration
writeln(message);
}
Fixing this one requies an external template that will create
your enum on the fly.
----------------
I'm thinking: While this is all surmountable, I'm pretty sure the
language could give us a easier time of this. We have the
possibility to declare and call a lambda both in one line. Why
not be able to declare a ctfe value as a 1-liner too?
I'm thinking, a simple cast: A cast to the "enum" type, which
explicitly means "this value needs to be compile time known".
Usage would look like:
enforce(pointer, cast(enum)format("Some message: %s",
some_static_args));
writeln(cast(enum)fib(5));
foreach(T; Types)
writeln(cast(enum)format("This type is %s.", T.stringof));
Here, we have some very simple code, no redundant variables, and
no run-time overhead.
I'm just throwing this out there to get some quick feedback
before filling an ER, or maybe a DIP.
Or, if somebody has an idea of how to do this via a library
solution?
Thoughts?
More information about the Digitalmars-d
mailing list