Using "cast(enum)" for explicit request of ctfe
luka8088
luka8088 at owave.net
Wed Dec 4 03:37:48 PST 2013
On 4.12.2013. 12:12, monarch_dodra wrote:
> 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?
You can use Eval template:
template Eval (alias value) {
alias value Eval;
}
writeln(Eval!(1 + 1));
enforce(pointer, Eval!(format("Some message: %s", some_static_args)));
Does this answer your question?
More information about the Digitalmars-d
mailing list