2011-08-29 20 views
7

是否有可能將nil作爲未聲明的常量傳遞給某些函數的無類型參數? 我有這樣的功能,我想通過一些不變的Data參數來滿足編譯器。我在內部決定使用Size參數。我知道我可以使用指針而不是無類型參數,但對我的情況來說更舒適。如何將「nil」常量傳遞給untyped參數?

現在我越來越E2250 There is no overloaded version of 'RS232_SendCommand' that can be called with these arguments

function RS232_SendCommand(const Command: Integer): Boolean; overload; 
begin 
    // is it possible to pass here an undeclared constant like nil in this example? 
    Result := RS232_SendCommand(Command, nil, 0); 
end; 

function RS232_SendCommand(const Command: Integer; const Data; const Size: Integer): Boolean; overload; 
begin 
    ... 
end; 

這工作,但我會很高興,如果我可以離開變量聲明。

function RS232_SendCommand(const Command: Integer): Boolean; overload; 
var 
    Nothing: Pointer; 
begin 
    Result := RS232_SendCommand(Command, Nothing, 0); 
end; 

解決方案是使用的財產以後這樣。

function RS232_SendCommand(const Command: Integer): Boolean; overload; 
begin 
    // as the best way looks for me from the accepted answer to use this 
    Result := RS232_SendCommand(Command, nil^, 0); 

    // or it also possible to pass an empty string constant to the untyped parameter 
    // without declaring any variable 
    Result := RS232_SendCommand(Command, '', 0); 
end; 

我這樣做是因爲我的一些命令在命令傳輸後發送了一個數據。

感謝您的幫助

回答

12

簡單:

RS232_SendCommand(Command, nil^, 0); 

您只需確保您不從內部訪問數據參數,但推測這是0尺寸參數的用途。

在我看來,這是最好的解決方案,因爲它非常明確地聲明你傳遞了一些無法訪問的東西。

+0

哇,這更聰明。我會接受這個答案,至少因爲有人提到這是不可能的。謝謝 – TLama

+0

是的,那是優雅的。 – Kaos

+1

我不確定'無'^可以歸類爲優雅! ;-)你只需要記住,這不會取消引用nil指針。 –

2

不,你不能。 不,我知道的

非類型參數

聲明 VAR常量,並參數時,可以省略型規格。 (值參數必須鍵入)。對於 例如:

過程TakeAnything(常量C);

聲明瞭一個名爲 TakeAnything接受任何類型的參數的過程。當你調用例如 例程時,你不能傳遞一個數字或無類型的數字常量。

來源:Parameters (Delphi)

所以,也許增加一個重載版本沒有const,ARG,你可以打電話的時候,大小= 0

+4

謝謝。這幫了我很多。從句子'你不能傳遞一個數字或無類型數字常量'我找到了一個方法,一個空字符串常量:'結果:= RS232_SendCommand(Command,'',0);' – TLama

+0

啊,很好的一個。 :) – Kaos