[fpc-pascal] Uniform initialization?
Sven Barth
pascaldragon at googlemail.com
Sun Nov 11 18:25:57 CET 2018
Am 11.11.2018 um 12:59 schrieb Ryan Joseph:
> 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???
I'm not convinced that this feature is really needed, because one can
simply create a constant and assign that, would transport a clear name
as well.
But *if* I had to decide I would pick #1, cause then there wouldn't be
the chance to break existing code if a user decides to add a constructor
to their record and some other code relies on there not being a
constructor. Also due to the syntax
TYPENAME(FIELDNAME:VALUE[;FIELDNAME:VALUE[;…]]) it's in principle
possible to have the parser distinguish whether it's a typecast or a
default constructor.
Regards,
Sven
More information about the fpc-pascal
mailing list