簡體   English   中英

使用ParameterTypeTuple測試功能簽名

[英]Testing function signatures with ParameterTypeTuple

我正在編寫帶有mixin模板的模塊,以提供用於單元測試目的的main功能。 用法如下:

/* For modules without their own main, e.g. libraries.
 * main is conditionally supplied using version(unittest).
 */
mixin Main;

/* For executable modules defining function "realMain".
 * Generated main has the same signature and return type
 * as realMain, and transfers control to it.  Additionally,
 * main exits without calling realMain for version (unittest).
 */
mixin Main!realMain;

這個想法是我的每個模塊都適當地混合在main模塊中,這樣:

  • 圖書館不需要--main傳給rdmd ,因為
  • 當為目錄層次結構中的每個文件自動運行單元測試時,似乎沒有一種好的方法來決定通過--main來定義自己的模塊。- rdmd的退出代碼與編譯失敗相同。

我正在使用std.traits確定realMain作為main函數的有效性,並確保生成的main具有相同的簽名。 一切似乎都正常,但我認為它可能更干凈。 目前,我用於檢查有效main參數的模板如下所示:

template isMainArgTypes(alias main)
{
    static if (is(ParameterTypeTuple!main == TypeTuple!()))
        enum isMainArgTypes = true;
    else static if (ParameterTypeTuple!main.length == 1
        && is(ParameterTypeTuple!main[0] T : const T[]))
    {
        enum isMainArgTypes = is(T : const char[]);
    }
    else
        enum isMainArgTypes = false;
}

我認為必須有某種方法可以將中間條件壓縮為單個is表達式,而無需顯式測試元組的長度並單獨檢查字符串類型,但是到目前為止,我的新生元編程還不足。

有什么想法嗎,D向導?

您可以嘗試將其與函數類型進行比較:

enum isMainArgTypes = is(typeof(&main) == int function()) || 
                      is(typeof(&main) == void function()) || 
                      is(typeof(&main) == int function(string[])) || 
                      is(typeof(&main) == void function(string[]));

不短,但看起來更干凈,因為它不需要static if

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM