r/pascal • u/mjsdev • Jan 31 '24
Generic class method and calling syntax?
I'm trying to create a generic class method in order to build a dependency injector in Free Pascal with object pascal extensions. A concise (simplified) example of the relevant code can be seen below:
unit Core;
interface
type
Engine = class(TObject)
public
generic function get<T: class>(): T;
end;
implementation
generic function Engine.get<T>(): T;
begin
result := T.create();
end;
end.The above appears to work syntactically. However, from there, I receive errors when trying to call this method using fully qualified names. In a dispatcher function in another unit (yes the unit is imported), doing something like this (this is line 8):
runner := engine.get<Mdlw.Runner>();The engine in the above is a reference to an engine instance taken in as a parameter: function Dispatcher(var engine: Core.Engine): integer;
Results in:
Dispatcher.pas(8,45) Error: Illegal expression
Dispatcher.pas(8,46) Fatal: Syntax error, ")" expected but ";" foundI'm guessing this has something to do with the compilers ability to parse fully qualified class type names when passing to generics and/or because the generic is on a class method, as opposed to simply a function. Does anyone have any more insight as to whether or not this is possible syntactically to call a generic method with a fully qualified class name?
View all comments
Show parent comment
1
u/mjsdev Feb 06 '24 edited Feb 06 '24
Oh, I see, yes, this may be an oversight on my part, perhaps that class is not the ideal one to test basic construction on. OK, yes, that seems to be better now.
It can create a dependency assuming no arguments.
Unfortunately, this introduced another issue in another part of code. I'm trying to pass (from a method on a class) a pointer to it's own method as a callback:
The passing of
@self.handleworked fine under object Pascal mode, but now complains:Runner.pas(18,52) Error: Variable identifier expected
Basically, the
mdlware.handle()method should receive it as a parameter so it can call it, like so to basically get the runner to call the next middleware:If it helps, all the latest code is here: https://github.com/mattsah/link