[英]How to create default value for reference argument for function in D?
我的功能簽名:
JSONValue get(string data, ref int parentCounter)
第二個參數必須通過引用傳遞,並且是可選的。 我的無效版本:
JSONValue get(string data, ref int parentCounter = 10);
JSONValue get(string data, ref int parentCounter = int(10));
JSONValue get(string data, ref int parentCounter = new int(10));
JSONValue get(string data); // override also does not work
DMD32 D編譯器v2.065
由於參數是ref
,因此必須有一個地址。 因此,它必須是一個左值表達式。
你可以這樣做:
JSONValue get(string data, ref int parentCounter = *new int);
您目前無法使用此語法來給新分配的int
一個值。 但是,在D 2.066中,您可以編寫:
JSONValue get(string data, ref int parentCounter = *new int(10));
除非在調用者站點上指定了一個新的int
,否則它將在堆上分配一個新的int
。
您還可以使用靜態變量或ref函數調用:
int defaultValue;
ref int defaultValueFun()
{
auto i = new int;
*i = 10;
return *i;
}
JSONValue get(string data, ref int parentCounter = defaultValue);
// or
JSONValue get(string data, ref int parentCounter = defaultValueFun());
警惕這種技術如果defaultValue
可能被稱為,而其參考value
仍在使用,雖然。
這時最簡單的解決方案可能就是重載該函數。 例如
JSONValue get(string data)
{
int dummy = 10;
return get(data, dummy);
}
JSONValue get(string data, ref int parantCounter)
{
...
}
它也避免了任何不必要的堆分配,這與Cybershadow建議在2.066退出后使用*new int(10)
的建議不同(盡管能夠進行*new int(10)
肯定很酷)。
現在,您似乎在問題中指出由於某種原因,重載該功能不起作用:
JSONValue get(string data); // override also does not work
因此,也許該解決方案對您不起作用,但是如果沒有更多信息,我不知道為什么不行。 當然,如果您要處理的是自由函數,則可以,如果您要處理的是struct成員函數,則可以。 我能想到的唯一可能的問題是,如果您要重寫基類函數,但是即使如此,我能想到的唯一問題是,如果基類聲明了
JSONValue get(string data, ref int parentCounter)
並且您試圖通過基類而不是派生類來調用該函數,並且如果這樣做,那么無論如何,在重寫函數中使用默認參數都無濟於事,因為基類沒有聲明一個-默認參數僅在通過派生類使用時才有效。 當然,您可以覆蓋基類的get
,然后在派生類中添加一個如下所示的重載:
JSONValue get(string data)
因此,如果聲明這樣的重載對您不起作用,我將需要更多詳細信息,以幫助您弄清為什么它不起作用。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.