Hello,
I have just come across a problem that I wanted to solve
using method pointers. In short, I have a class containing
a list of other classes. I have a separate iterator class
that can iterate through the container class in various
ways, performing various actions.
Now what I'd like to do is to be able to pass a class
method pointer to this iterator, saying something like:
for each item you find in the container, call method
'GetX' of this container item.
This seems to be impossible to do, because (If I am correct,
please prove me wrong) method pointers always point to a
method of a specific object. It seems to be impossible to
define method pointers that point to a method of a class,
so that you can later say 'now do your
stuff on this instance of the class'.
What I'm basically asking is: is there something I've
overlooked? I hope there is, even though it's only a small
problem and there's an easy workaround. It's just that it
seems so easy to do (and I've done it in C++, which on the
other hand does not have object method pointers but only
class method pointers (at least last time I checked))
In case all this has become a bit unclear, I put some code
below to show you what I'm trying to do (and what I'm doing
instead at this moment).
Greetings,
Eric.
PS: Example:
class TFoo
...
function GetX:longint;
function GetY:longint;
...
class function ClassGetX(obj:TFoo):longint;
end;
class TFooContainer
list:TFooList;
...
end;
class TFooIterator
function First:TFoo;
function Next:TFoo;
...
function ForEach(func:classmethod):longint;
...
end;
implementation
function TFooIterator.ForEach(func:classmethod):longint;
var foo:TFoo;
total:longint;
begin
total:=0;
foo:=First;
while foo<>nil do
begin
{ type func = function:longint of class }
Inc(total, foo^.func);
^^^^^^^^^^^^^^^^^^^^^
This seems to be impossible...
{ type func = function(obj:TFoo):longint of object }
Inc(total, func(foo));
^^^^^^^^^^^^^^^^^^^^^
This works but requires an extra 'getter' for each
method of foo I want to access
foo:=Next;
end;
end;
procedure DoSomething(TFooContainer foos);
var iter:TFooIterator;
begin
iter:=TFooIterator.Create(foos);
iter.ForEach(TFoo.GetX);
{ func = function:longint of class }
{ The compiler doesn't like this syntax... }
iter.ForEach(TFoo.ClassGetX);
{ func = function(obj:TFoo):longint of object }
{ This one works }
iter.Free;
end;