PDA

View Full Version : Making a function return anything... or something like that.



pstudio
23-12-2011, 07:53 PM
Using FPC 2.7.1

Ok, I've got a base class with a function definition like this:



TBase = class
public
class function Foo(Args: array of const) : TVarRec; virtual;
end;


Now imagine there are several classes inheriting TBase...



TClassA = class(TBase)...
TClassB = class(TBase)...
TClassC = class(TBase)...

class function TClassA.Foo(Args: array of const) : TVarRec;
begin
TSomeObject(Args[0].VObject).DoSomeThingCoolToThisObject; // Args[0] is an object
Result := Args[0];
end;

class function TClassB.Foo(Args: array of const) : TVarRec;
var
int: Integer;
begin
int := Args[0].VInteger; // Args[0] is an integer
Result := Args[0]
end;

class function TClassC.Foo(Args: array of const) : TVarRec;
begin
TSomeObject(Args[0].VObject).DoSomeThing(Args[1].VInteger); //Args[0] is an object - Args[1] is an integer
end;


The idea is that these functions can be called using the other functions (their results) as arguments. E.g.



TClassC.Foo(TClassA.Foo(TSomeObject).VObject, TClassB.Foo(1337).VInteger);


This works fine but I think it is a but ugly that I have to specify which type is returned every time. It would be nicer if I could call the functions like this:



TClassC.Foo(TClassA.Foo(TSomeObject), TClassB.Foo(1337));


Does anyone know if there is a way to achieve this? The classes must derive from TBase which defines a function that can take anything as arguments and return something. Is it possible or does it contradict too much with the type system?

Ñuño Martínez
11-01-2012, 05:27 PM
Not sure if it will work in your case, but may be you can use the DEFAULT property modifier.