Counting at compile-time

Bradley Chatha sealabjaster at gmail.com
Sun Jan 26 16:43:23 UTC 2025


On Sunday, 26 January 2025 at 15:42:44 UTC, DLearner wrote:
> But how to get that value into Count?

It's hard to say what would exactly fit your use case since this 
is just a minimal example, so it's hard to gauge what other 
restrictions and inputs exists, but if your logic is a bit more 
complex then CTFE (Compile Time Function Execution) might be a 
viable option:

```d
int myCount(bool Cond1, bool Cond2)()
{
     // Assumes that the code is more complex, so you can't easily 
use something similar to:
     // count = cast(int)Cond1 + cast(int)Cond2;

     int count = 0;

     static if(Cond1)
         count++;

     static if(Cond2)
         count++;

     return count;
}

pragma(msg, myCount!(false, false)); // 0
pragma(msg, myCount!(true, false)); // 1
pragma(msg, myCount!(false, true)); // 1
pragma(msg, myCount!(true, true)); // 2

// e.g. store it in an enum
enum Count = myCount!(true, false);

// Or more simply... if possible for your use case
enum Cond1 = true;
enum Cond2 = false;
enum Count = cast(int)Cond1 + cast(int)Cond2; // cast(int)true == 
1; cast(int)false == 0
```

Without additional context it's hard to give a concrete 
suggestion though, but I hope this helps.


More information about the Digitalmars-d-learn mailing list