[fpc-pascal] Uniform initialization?

Ryan Joseph ryan at thealchemistguild.com
Sun Nov 11 12:59:22 CET 2018


Since I’ve got a little more free time I wanted to see if there was a simple solution to issue in Pascal that causes quite a bit of friction for me, i.e. constructor boiler plate. In c++ there is “uniform initialization” for structs which uses the {} syntax. It’s basically identically to record consts in Pascal, i.e.

type
  tvec2 = record
    x,y:integer;
  end;

var
  vec: tvec2 = (x:1;y1);

but it can be used at runtime (unlike Pascal which is compile time only). Many months ago I mentioned this and got a little positive response so I’d to ask again since I could probably implement it now.

Are any of these ideas appealing?

1) Simply move the typed const syntax down into blocks and use the type name like a function i.e.,

var
 vec:tvec2;
begin
 vec := tvec2(x:1;y1);

2) providing advanced records are on and perhaps a mode switch or some other kind of decorator, auto generate an implicit constructor, given no other constructors named “create" in the structure exist. i.e.,

{$something+}
type
  tvec2 = record
    x,y:integer;
  end;
{$something-}

var
 vec:tvec2;
begin
  vec := tvec2.create(1,1); // tvec2 has no constructor defined so “create” with all public member fields as parameters is implicitly defined
  vec := tvec2.create;	// “create” is a static class function with default values so we can do this
end.

Here is the proposed implicit constructor for tvec2:

class function create(_x:integer=default(integer);y:integer=default(integer)):tvec2;static;

I prefer #2 because it’s easiest to type and looks most natural to Pascal. Not sure what the downsides are even???

Regards,
	Ryan Joseph




More information about the fpc-pascal mailing list