【发布时间】:2014-07-04 21:34:27
【问题描述】:
在 C/C++ 中,我们有预处理器指令(参见问题的标题)。它们在 D 语言中的类比是什么? 以及如何在编译时检测操作系统类型(Windows、Linux、Mac OS X、FreeBSD...)和处理器类型(例如:32 位或 64 位)?
【问题讨论】:
标签: preprocessor d
在 C/C++ 中,我们有预处理器指令(参见问题的标题)。它们在 D 语言中的类比是什么? 以及如何在编译时检测操作系统类型(Windows、Linux、Mac OS X、FreeBSD...)和处理器类型(例如:32 位或 64 位)?
【问题讨论】:
标签: preprocessor d
更新:最佳答案已在 dlang.org 上:http://dlang.org/pretod.html。
D 没有预处理器。相反,它提供了强大的编译时评估和自省功能。
以下是典型的 C/C++ 到 D 翻译的简单列表,以及相关文档的链接:
C/C++:#ifdef、#ifndef、#else、#elif
D:version [link]
C/C++:#if <condition>
D:static if [link]
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));
}
(Example taken from the D wiki)
C/C++:#undef
D:据我所知没有足够的翻译
【讨论】:
#if defined(X) 呢?
#if condition 被 static if(condition) 替换(编译时间评估更多)
#ifdef ident 替换为version(ident)
#define ident 替换为version = ident
#define ident replacement 替换为alias ident replacement
更多信息http://dlang.org/version.html和predefined version defines列表
【讨论】:
这对于 C 与 D 中的预处理器指令可能有些用处: http://dlang.org/pretod.html
关于操作系统和处理器类型的检测,这个帖子看起来可能会回答你的问题:http://forum.dlang.org/thread/mailman.616.1387191250.3242.digitalmars-d-learn@puremagic.com?page=1
注意:我熟悉 C/C++ 但不熟悉 D。如果我的答案不充分,请告诉我,以便我更改。希望我已经为您指明了正确的方向。
【讨论】:
模拟 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;
【讨论】: