Thoughts about "Compile-time types" talk

Martin Tschierschke mt at smartdolphin.de
Mon May 13 08:35:39 UTC 2019


On Friday, 10 May 2019 at 00:33:04 UTC, H. S. Teoh wrote:
[...]

> I haven't fully thought through this yet, but the basic concept 
> is that there should be *no need* to distinguish between 
> compile-time and runtime in the general case, barring a small 
> number of situations where a decision has to be made.
[...]
I was thinking and working in the same direction,
when using regEx you can use the runtime (RT) or the compile time 
(CT) version,
but why not let the compiler make the decisions?

The solution was from someone else, in the forum, but it resulted 
in the following code:

auto reg(alias var)()
{
        static if (__traits(compiles, {enum ctfeFmt = var;}) )
          {
                 // "Promotion" to compile time value
                 enum ctfeReg =  var ;
                 pragma(msg, "ctRegex used");
                 return(ctRegex!ctfeReg);

           }else{
                 return(regex(var));
                 pragma(msg,"regex used");
           }
}

The trick is the alias var, which then can be checked,
with
       __traits(compiles, {enum ctfeFmt = var;}

is it an immutable value present at compiletime or not.


Now you may use

auto myregex = reg!(Regex_expression);

At every place in your code.

And depending on the question, does it compile to the ctfeReg or 
not the version is selected.

So there is away to promote a ctVariable to runtime, if this 
would be possible with a runtime value, too, you would get rid of 
the '!' -syntax.

Regards mt.




More information about the Digitalmars-d mailing list