Is there a way to make a function parameter accept only values that can be checked at compile time?

rempas rempas at tutanota.com
Wed Dec 29 09:09:34 UTC 2021


On Wednesday, 29 December 2021 at 01:34:22 UTC, Stanislav Blinov 
wrote:
> One can also do this kind of stuff:
>
>
> ```d
> import core.stdc.stdio;
>
> struct Literal(alias val)
> {
>     enum value = val;
> }
>
> enum lit(alias val) = Literal!val.init;
>
> void print_num(Arg)(int num, Arg mul)
> {
>     static if (is(Arg == Literal!val, alias val))
>     {
>         static if (is(typeof(val) == string))
>             printf("mul by compile-time string \"%s\"!\n", 
> val.ptr);
>         else static if (is(typeof(val) == int) && (val == 3))
>             printf("mul by compile-time 3!\n");
>         else
>             printf("mul by compile-time thing\n");
>     }
>     else
>     {
>         printf("mul by runtime thing\n");
>     }
> }
>
> void main()
> {
>     print_num(10, lit!"hello"); // mul by compile-time string 
> "hello"!
>     print_num(10, lit!3);       // mul by compile-time 3!
>     print_num(10, lit!'a');     // mul by compile-time thing
>     print_num(10, 10);          // mul by runtime thing
> }
> ```

Thanks! That's awesome tho It will be annoying to have to type 
"lit!3" and not just pass it a literal or an "enum" or anything 
else that is guaranteed to be able to read at compile time.


More information about the Digitalmars-d-learn mailing list