Search code examples
templatesd

Why use static if in D?


I have been reading about the template system in the D language and came upon a unusual construct, static if.

From what I managed to grasp it is evaluated at compile time, but from what I have searched, the example shown here did not quite enlighten me.

template Factorial(ulong n)
{
    static if(n < 2)
        const Factorial = 1;
    else
        const Factorial = n * Factorial!(n - 1);
}

What does static if do, and when should I use it?


Solution

  • the D static if is the base for "conditional compilation", and plays an important role wherever a compile time decision about a variant of a code must be taken.

    Since D doesn't have a preprocessor, things like

    #ifdef xxx
    compile_this_piece_of_code
    #endif
    

    can become

    static if(xxx)
    {
         compile_this_pece_of_code
    }
    

    similarly, metaprogramming can happen also via static if:

    template<int x>
    struct traits
    { some definition calculated from x };
    
    template<>
    struct traits<0>
    { same definitions for the 0 particular case }
    

    can be

    template(int x)
    {
        static if(x==0)
        { some definitions }
        else
        { some other same definitions }
        even more definition common in the two cases
    }