D 程式設計 - 條件編譯



條件編譯是選擇編譯哪些程式碼以及不編譯哪些程式碼的過程,類似於C和C++中的`#if`/`#else`/`#endif`。任何未編譯的語句都必須在語法上正確。

條件編譯涉及在編譯時可評估的條件檢查。執行時條件語句(如if、for、while)不是條件編譯特性。D語言的以下特性用於條件編譯:

  • debug
  • version
  • static if

D語言中的除錯語句

在程式開發過程中,`debug`非常有用。僅當啟用-debug編譯器開關時,標記為debug的表示式和語句才會編譯到程式中。

debug a_conditionally_compiled_expression;
   
debug { 
   // ... conditionally compiled code ... 
} else { 
   // ... code that is compiled otherwise ... 
}

else子句是可選的。只有當啟用-debug編譯器開關時,才會編譯單個表示式和上面的程式碼塊。

這些行不會被完全刪除,而是可以標記為debug。

debug writefln("%s debug only statement", value); 

只有當啟用-debug編譯器開關時,這些行才會包含在程式中。

dmd test.d -oftest -w -debug 

D語言中的Debug(tag)語句

可以為除錯語句命名(標籤)以便選擇性地包含在程式中。

debug(mytag) writefln("%s not found", value);

只有當啟用-debug編譯器開關時,這些行才會包含在程式中。

dmd test.d -oftest -w -debug = mytag

debug塊也可以有標籤。

debug(mytag) { 
   //  
}

可以一次啟用多個debug標籤。

dmd test.d -oftest -w -debug = mytag1 -debug = mytag2

D語言中的Debug(level)語句

有時,按數值級別關聯除錯語句更有用。更高的級別可以提供更詳細的資訊。

import std.stdio;  

void myFunction() { 
   debug(1) writeln("debug1"); 
   debug(2) writeln("debug2");
}

void main() { 
   myFunction(); 
} 

將編譯低於或等於指定級別的debug表示式和塊。

$ dmd test.d -oftest -w -debug = 1 
$ ./test 
debug1 

D語言中的Version(tag)和Version(level)語句

Version類似於debug,使用方法相同。else子句是可選的。雖然version的工作原理與debug基本相同,但使用單獨的關鍵字有助於區分它們不相關的用途。與debug一樣,可以啟用多個version。

import std.stdio;  

void myFunction() { 
   version(1) writeln("version1"); 
   version(2) writeln("version2");     
}
  
void main() { 
   myFunction(); 
}

將編譯低於或等於指定級別的debug表示式和塊。

$ dmd test.d -oftest -w -version = 1 
$ ./test 
version1 

Static if

Static if是if語句的編譯時等價物。就像if語句一樣,static if接受一個邏輯表示式並對其進行評估。與if語句不同的是,static if與執行流程無關;它確定是否應將一段程式碼包含在程式中。

if表示式在語法和語義上都與我們之前看到的is運算子無關。它在編譯時計算。它生成一個int值,0或1;取決於括號中指定的表示式。雖然它接受的表示式不是邏輯表示式,但is表示式本身用作編譯時邏輯表示式。它在static if條件和模板約束中特別有用。

import std.stdio;

enum Days { 
   sun, 
   mon, 
   tue, 
   wed, 
   thu, 
   fri, 
   sat 
}; 
 
void myFunction(T)(T mytemplate) {
   static if (is (T == class)) { 
      writeln("This is a class type"); 
   } else static if (is (T == enum)) { 
      writeln("This is an enum type"); 
   } 
}
  
void main() { 
   Days day; 
   myFunction(day); 
} 

編譯並執行後,我們將得到如下輸出。

This is an enum type
廣告