为什么在D中使用static? [英] Why use static if in D?
问题描述
我一直在用D语言阅读模板系统,并遇到了一个不寻常的结构,静态if
。
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?
推荐答案
D 静态if
是条件编译的基础,并且在必须做出有关代码变体的编译时决定的任何地方都起着重要作用。
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.
由于D没有, t有一个预处理器,例如
Since D doesn't have a preprocessor, things like
#ifdef xxx
compile_this_piece_of_code
#endif
可以成为
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 }
可以是
template(int x)
{
static if(x==0)
{ some definitions }
else
{ some other same definitions }
even more definition common in the two cases
}
这篇关于为什么在D中使用static?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!