为什么在D中使用静态?

cor*_*ump 8 templates d

我一直在阅读D语言中的模板系统,并发现了一个不寻常的结构,static if.

根据我设法掌握的内容,它在编译时进行了评估,但是从我搜索的内容来看,这里显示的示例并没有给我带来太多启发.

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

static if什么,什么时候应该使用它?

Emi*_*lia 13

D static if是"条件编译"的基础,并且在必须采用编译时决定代码变体的任何地方都起着重要的作用.

因为D没有预处理器,所以像

#ifdef xxx
compile_this_piece_of_code
#endif
Run Code Online (Sandbox Code Playgroud)

可以变成

static if(xxx)
{
     compile_this_pece_of_code
}
Run Code Online (Sandbox Code Playgroud)

类似地,元编程也可以通过静态发生,如果:

template<int x>
struct traits
{ some definition calculated from x };

template<>
struct traits<0>
{ same definitions for the 0 particular case }
Run Code Online (Sandbox Code Playgroud)

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