Check if function argument can be handled in CT

Mike Parker aldacron at gmail.com
Wed Apr 24 11:34:22 UTC 2019


On Wednesday, 24 April 2019 at 10:52:58 UTC, Andrey wrote:
> On Wednesday, 24 April 2019 at 08:28:06 UTC, Basile.B wrote:
>> On Wednesday, 24 April 2019 at 07:53:47 UTC, Andrey wrote:
>
> I know about this template. Unfortunally, it doesn't work 
> inside functions.
>> void test(string arg1, string arg2)
>> {
>>     enum isKnown1 = is(typeof((){enum v = arg1;}));
>>     enum isKnown2 = is(typeof((){enum v = arg2;}));
>>     writeln(isKnown1);
>>     writeln(isKnown2);
>> }
>> 
>> void main()
>> {
>>     test("qwerty", "qaz");
>> }
>
> Output:
>> false
>> false
>
> And I don't want to execute function using CTFE. The function 
> should be ran as usual.
>
> Example:
>> char[] test(string arg1, string arg2)
>> {
>>     static if(isCTArg(arg1) && isCTArg(arg2))
>>     {
>>         enum result = "CT: " ~ arg1 ~ " and " ~ arg2; // no 
>> allocations
>>         return result;
>>     }
>>     else
>>     {
>>         import std.format : format;
>> 
>>         auto result = format!"RT: %s and %s"(arg1, arg2); // 
>> at least 1 allocation
>>         return result;
>>     }
>> }
>> 
>> void main()
>> {
>>     // ...
>>     auto val = test(some_CT_or_RT_arg1, some_CT_or_RT_arg2); 
>> // not CTFE.
>>     // ...
>> }

arg1 and arg2 are *never* compile-time arguments. If a function 
is executed at compile time, the function may be passed arguments 
that are compile-time values, but inside the function, the 
arguments are interpreted as if it were running at runtime. That 
means that you can't assign function arguments to enums.


More information about the Digitalmars-d-learn mailing list