Kaos
Kaos

Reputation: 1004

Delphi: Generic type inference of reference argument

What's the best way to get around the shortcoming of generic type inferencing of reference arguments, so that I don't have to specify the type in every call?

Update: I don't mind other (including non-generic) solutions as long as it works with multiple (any?) types.

This seems to still not have been resolved, although known for quite some time.

Please vote for a resolution to this on Embarcaderos Quality Central: Issue #78103.

From a comment by Barry Kelly to Generic Methods and Type Inferencing:

PS: Your example, in Tiburon, almost works. Method type inference works well for arguments passed by value. It doesn’t work for arguments passed by reference, unfortunately (the compiler is being too strict).

Now, almost three years later, I'm trying the same thing in Delphi XE, and it complains that:

[DCC Error] INIv1_Parser.pas(81): E2033 Types of actual and formal var parameters must be identical

When calling:

function FindDataItemValue<T>(ItemType: TDataItemType; out Value: T): Boolean;

With:

var MaxG: Real;
...
if Data.FindDataItemValue(PAR_MaxG, MaxG) and (MaxG = 2.5) then ...

Commonly suggested work-around: However, if I add the generalization on the call, it works fine; although annoying that it is even needed.

Update:

Thus far, The best I've come up with is to use either Variants or the TValue record from the Rtti module. Using variants I implement interfaces when I need to use objects, and store a reference to that (interface) in the variant.

Upvotes: 2

Views: 799

Answers (3)

Thorsten Engler
Thorsten Engler

Reputation: 2371

Type inference does not currently work for var and out parameters. I agree that it is highly annoying.

Upvotes: 3

Jeroen Wiert Pluimers
Jeroen Wiert Pluimers

Reputation: 24523

There is no workaround. You have to specify the type.

var
  MaxG: Real;
...
  if Data.FindDataItemValue<Real>(PAR_MaxG, MaxG) and (MaxG = 2.5) then ...

If you want Embarcadero to resolve this, then vote for this QC entry that is about your issue.

The QC entries with the highest votes get more attention.

Upvotes: 1

Rob Kennedy
Rob Kennedy

Reputation: 163357

The best way is to do exactly what's demonstrated in the article you cite: Include the type parameters in the method call:

if Data.FindDataItemValue<Real>(PAR_MaxG, MaxG) ...

Upvotes: 0

Related Questions