1
votes

I'm trying to convert some Free Pascal code to compile with Delphi 10.2.

The Free Pascal code is structured like this:

generic TVolume<T> = class(TObject)
    // T has to be a numerical/float type
    constructor Create(pSizeX, pSizeY, pDepth: integer; c: T = 0);
    constructor Create(Original: TBits; pFalse: T = -0.5; pTrue: T = +0.5);

Delphi doesn't like this: E2268: Parameters of this type cannot have default values

I think the reason is simply that the Delphi compiler doesn't want to make assumptions of what type T might be, so it refuses to compile this. This point goes to FPC I'd say.

To workaround this, I most likely have to create a bunch of overload methods:

TVolume<T> = class(TObject)
    constructor Create(pSizeX, pSizeY, pDepth: integer); overload;
    constructor Create(pSizeX, pSizeY, pDepth: integer; c: T); overload;

    constructor Create(Original: TBits); overload;
    constructor Create(Original: TBits; pFalse: T); overload;
    constructor Create(Original: TBits; pFalse: T; pTrue: T); overload;

But I still wonder if there is a way a to do this in Delphi, which I'm not aware of yet?

1

1 Answers

2
votes

The simple answer to this question is:

No, there is no way to pass default parameters to a Generic type T in Delphi, because the type of T is not known at the time of declaration. And since Delphi is a single-pass compiler, it does not allow this.

Free Pascal implements a 2-pass processing of Generics. Thats why it can delay the code generation for a Generic until it encounters a specialization at implementation.

In this specific case, we discovered that a Generic declaration of TVolume is not even required anyway. In the entire Free Pascal project, TVolume<T> is implemented only once as TNNetVolume = class (specialize TVolume<TNeuralFloat>). TNeuralFloat is of type Single. So the Generic declaration of TVolume<T> can be changed to TVolume and all references of T can be replaced with TNeuralFloat. This works and can be compiled in Delphi.

Thanks to Rudy Velthuis , Remy Lebeau and David Heffernan for their help and contribution to sort this out. :)