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 08:55:32 UTC 2021


On Tuesday, 28 December 2021 at 22:06:50 UTC, Steven 
Schveighoffer wrote:
> On 12/28/21 4:19 PM, rempas wrote:
>
> Here:
>
>> ```
>> extern (C) void main() {
>>    void print_num(int mul)(int num) {
>>      static if (is(mul == ten)) {
>>        printf("%d\n", num * 10);
>>      } else static if (is(mul == three)) {
>>        printf("%d\n", num * 3);
>>      } else {
>>        printf("%d\n", num);
>>      }
>>    }
>> 
>>    int multi = 211;
>>    print_num!3(10);     // Ok, accept this
>>    print_num!multi(10); // Error, do not accept this
>> }
>> ```
>
> -Steve

Thanks! That's cool but I don't want this to be this way. Or at 
least I want it to be able to take a default value so we don't 
have to get passed all the time. So something like this:

```
extern (C) void main() {
   void print_num(int num, comp_time_type int mul = 100) {
     static if (is(mul == ten)) {
       printf("%d\n", num * 10);
     } else static if (is(mul == three)) {
       printf("%d\n", num * 3);
     } else {
       printf("%d\n", num);
     }
   }

   int multi = 211;
   print_num(10, 3);     // Set the value
   print_num(30);        // Get the default value, have the "else" 
branch executed
}
```

Is this possible?



More information about the Digitalmars-d-learn mailing list