D编程语言中的 analgs 是什么,分别对应于 "#ifdef"、"#ifndef"、"#else"、"#elif"、"#define" 和 "#undef"?

7
在C/C++中,我们有预处理器指令(见问题标题)。那么,在D语言中,它们的类比是什么? 如何在编译时检测操作系统类型(Windows、Linux、Mac OS X、FreeBSD等)和处理器类型(例如:32位或64位)?
4个回答

9

更新:最佳答案已经在dlang.org上了:http://dlang.org/pretod.html

D语言没有预处理器。相反,它提供了强大的编译时评估和内省能力。

以下是一个简单的C/C++到D语言翻译列表,其中包含相关文档的链接:


C/C++#ifdef#ifndef#else#elif

Dversion [链接]


C/C++#if <condition>

Dstatic if [链接]


C/C++#define

D:D语言的翻译取决于具体情况。

#define FOO这样的简单C/C++定义被翻译成D语言的"version"。例如:version = FOO

#define BAR 40这样的代码被翻译成以下D语言代码:enum BAR 40,或者在极少数情况下,您可能需要使用alias

#define GT_CONSTRUCT(depth,scheme,size) \ ((depth) | (scheme) | ((size) << GT_SIZE_SHIFT))这样的复杂定义被翻译为D语言的模板:

// Template that constructs a graphtype
template GT_CONSTRUCT(uint depth, uint scheme, uint size) {
  // notice the name of the const is the same as that of the template
  const uint GT_CONSTRUCT = (depth | scheme | (size << GT_SIZE_SHIFT));
}

(本例节选自D语言维基)


C/C++: #undef

D: 我所知道的没有一个合适的翻译


#if defined(X)是什么意思? - user1461607

8

#if condition被替换为static if(condition)(具有更多的编译时评估)

#ifdef ident被替换为version(ident)

#define ident被替换为version = ident

#define ident replacement被替换为alias ident replacement

更多信息请参见http://dlang.org/version.html,以及预定义版本定义列表


3

1

模拟 ifndef。 这里是检测符号存在的测试:

如果未定义 FT_THROW,则定义默认函数 FT_THROW。这类似于带有 ifndef 的常见代码。

import std.stdio;

// my implementation of FT_THROW
void FT_THROW( int x ) { writeln( "calling redefined FT_THROW(): ", x*x ); }

// ifndef FT_THROW
static if ( !is( typeof( FT_THROW ) ) )
{
    pragma( msg, "FT_THROW not exists. using default implementation." );

    // default implementation of FT_THROW
    void FT_THROW( int x ) { writeln( "call FT_THROW(): ", x ); }
}


void main()
{
    // ifdef FT_THROW
    static if ( is( typeof( FT_THROW ) ) )  // checking for FT_THROW extsts
    {
        pragma( msg, "FT_THROW found" );
    }

    FT_THROW( 7 );
}

在线演示: https://run.dlang.io/is/N3ENqb

实际例子:

#ifndef FT_MEM_ZERO
#define FT_MEM_ZERO( dest, count )  FT_MEM_SET( dest, 0, count )
#endif

static if ( !is( typeof( FT_MEM_ZERO ) ) ) 
{
    auto FT_MEM_ZERO( T1, T2 )( T1 dest, T2 count )  { FT_MEM_SET( dest, 0, count ); }
}

例子2:
#ifndef TRUE
#define TRUE   1
#endif

static if ( !is( typeof( TRUE ) ) ) 
    enum TRUE = 1;

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接