• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 323
  • Last Modified:

Delphi to C++ (procedure of object)

I wonder how the following snippet will appear in C++.

type
  TFoo = procedure(i: integer) of object;
var
  foo: TFoo;
...
foo := Bar.Foo;
foo(2);
0
__alex
Asked:
__alex
2 Solutions
 
kretzschmarCommented:
0
 
__alexAuthor Commented:
Interesting, indeed...
0
 
CayceCommented:
Something like this:

class Bar
{
public:
  static void Foo(int i) {}
};

typedef void (*TFoo)(int i);
/*...*/
void main()
{
  TFoo foo;
  Bar a;
  foo = &a.Foo;
  foo(2);
}
0
Get expert help—faster!

Need expert help—fast? Use the Help Bell for personalized assistance getting answers to your important questions.

 
__alexAuthor Commented:
Hi Cayce,
I don't want my Bar.Foo method to be static :-(
0
 
andrewjbCommented:
You can't directly. You can store a pointer to a class function, but to call it you need to supply the class instance too.

Roughly like:

class ToCall
{
  void SomeFunction( int x ) {...}
};

typedef void (ToCall::*FnType)(int);

FnType MyPointer = &ToCall::SomeFunction;

then

ToCall x;

(x.*MyPointer)(10);



So, if you want to store it in a Delphi-like way, you need a class which stores a) the class instance, and b) the pointer reference

class tMyDelphiLikePointer
{
 typedef void (ToCall::*FnType)(int);
  FnType   fFn;
  ToCall *fInstance;

  void CallIt( int a ) { (ToCall.*fFn)(a); };
};

(Roughly! Havne't tried compiling these!)

.. and there might be an alternative that I don't know about yet!

0
 
__alexAuthor Commented:
Ok, got it. But I need a bunch of classes if I have different "target object" types or use templates, do I?
foo := Bar_1.Foo;   // Bar_1 is TBar_1
foo := Bar_2.Foo;   // Bar_2 is TBar_2
That gets complicated...
0
 
__alexAuthor Commented:
0
 
andrewjbCommented:
Have stored the link but not read yet...

Answer is templates if you've lots of class types.
0

Featured Post

[Webinar] Improve your customer journey

A positive customer journey is important in attracting and retaining business. To improve this experience, you can use Google Maps APIs to increase checkout conversions, boost user engagement, and optimize order fulfillment. Learn how in this webinar presented by Dito.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now