Re: Non-static member function as a callback

Tech-Archive recommends: Repair Windows Errors & Optimize Windows Performance

From: Arnaud Debaene (adebaene_at_club-internet.fr)
Date: 11/23/04


Date: Wed, 24 Nov 2004 00:18:31 +0100

Agoston Bejo wrote:
> Hi,
> I would like to do something like this:
>
>
> struct A {
> int f(float f);
> };
> ...
>
> int g(int(*f1)(float)) { return f1(6.5); }
>
> int main() {
> A a;
> g(a.*f); // or whatever. This won't compile, of course
> }
>
>
> Is this possible? If so, then how?

As steve as explianed, a member function pointer is not a simple function
pointer because :
- the member function takes an additrionnal, hidden, "this" parameter.
- the pointer itself may need to embed more information that just the
function address, in order to be able to call the right override in case of
virtual function. That's why the effective size of a member function pointer
can vary from 4 to 16 bytes, depending on the class hierarchy.

One possible solution to your problem is to replace your simple function
pointer in g by a template parameter, and then use boost::bind to create a
nullary functor calling your objec tinstance member function :

struct A
{
  int f(float val);
};

template <typename FunctorType> int g(FunctorType functor)
{
   return functor(6.5);
}

int main
{
   A a;
   g (boost::bind(&A::f, a));
}

See www.boost.org for details.

Arnaud
MVP - VC



Relevant Pages

  • Re: Non-static member function as a callback
    ... > struct A { ... > int f; ... a member function pointer is not a simple function ...
    (microsoft.public.dotnet.languages.vc)
  • Re: Members or not
    ... > For an equality operator 2 should be prefered. ... > struct X ... > int main ... > By using a member function instead of a free function you impose different ...
    (comp.lang.cpp)
  • Template parameter to member function problem
    ... I have a class template that takes an argument to a class and an ... argument to a member function of the given class. ... struct B { ... int main ...
    (comp.lang.cpp)
  • Re: Member Functions
    ... of instances of struct S and that each instance of this struct ... If I were to implement this as a class with a member function ... instead of the function pointer, ... int Func ...
    (alt.comp.lang.learn.c-cpp)
  • Re: No argument on the command line! (Only solutions present)
    ... printf function. ... int main ( ... Note string display result data type int, double char is same. ... Member function setf ...
    (sci.math)