Static ternary if

lqjglkqjsg via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Mon Jul 25 06:04:18 PDT 2016


On Monday, 25 July 2016 at 05:00:23 UTC, Ali Çehreli wrote:
> On 07/24/2016 07:15 PM, Gorge Jingale wrote:
>> Is there a static ternary if?
>>
>> (A == B) ? C : D;
>>
>> for compile type that works like static if.
>
> The way to force an expression at compile time is to use it for 
> something that's needed at compile time. For example, you can 
> initialize a manifest constant (enum) with that expression:
>
> void main() {
>     enum i = (__MODULE__.length % 2) ? 42 : 43;
>     pragma(msg, i);
> }
>
> Instead of enum, you can use 'static const' as well.
>
> Ali

It also works for "real" enumerated types.

********************************
enum ver = 0; // version(Windows) ... else ....

enum VersionRelative1
{
     A = ver ? 1 : 2,
     B = ver ? 3 : 4,
}

enum VersionRelative2
{
     A = !ver ? 1 : 2,
     B = !ver ? 3 : 4,
}

unittest
{
     static assert(VersionRelative1.A == 2);
     static assert(VersionRelative2.A == 1);
}
********************************

which is quite cool and not widely known.


More information about the Digitalmars-d-learn mailing list