Trojanian
Trojanian

Reputation: 752

How to define a constant record containing other constant records in Delphi? Specific case: matrix using vectors

Say I have a simple record in a unit, such as:

TVector2D = record
public
  class function New(const x, y: Accuracy): TVector2D; static;
public
  x, y: Accuracy;
end;

I then have a second record in the same unit that is built using a set of the above records, such as:

TMatrix3D = record
public
  class function New(const row1, row2, row3: TVector3D): TMatrix3D; static;
public
  Index : array [0..2] of TVector3D;
end;

I then define axis direction constants as follows:

//Unit vector constants
const
  iHat : TVector3D = (x: 1; y: 0; z: 0);
  jHat : TVector3D = (x: 0; y: 1; z: 0);
  kHat : TVector3D = (x: 0; y: 0; z: 1);

I want now to define a further constant using the above constants, something like:

  identity : TMatrix3D = (row1: iHat; row2: jHat; row3: kHat);

Yet the above attempt doesn't work. How would I do this in Delphi XE2?

Many thanks in advance for your efforts. :-)

Upvotes: 8

Views: 12012

Answers (1)

David Heffernan
David Heffernan

Reputation: 613013

That's not possible. In a constant record declaration, the member values must be constant expressions. That is, you cannot use typed constants as you have attempted to do.

The documentation says it like this, with my emphasis:

Record Constants

To declare a record constant, specify the value of each field - as fieldName: value, with the field assignments separated by semicolons - in parentheses at the end of the declaration. The values must be represented by constant expressions.

So you need to declare it like this:

const
  identity: TMatrix3D = (Index:
    ((x: 1; y: 0; z: 0),
     (x: 0; y: 1; z: 0),
     (x: 0; y: 0; z: 1))
    );

Frustrating to have to repeat yourself, but this is the best you can do I suspect.

Upvotes: 18

Related Questions