Re: Passing a member function to another func.

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



dududuil wrote:
Hi,
I am trying to pass one class member (NOT STATIC!) to another func,
and fail to compile.
I try to do something like this:

struct A { void fa1(); void fa2(); };

struct B {
void (*m_fb)();
void SetFA(void (*fa)()) {m_fb = fa;};
};

void main()
{
A a;
B b;
b.SetFA( &a.fa1 ); // Compile error: C2276!!!
}

Note: func A::fa can not be static.

How can I do this?
What I want is to decide on run time, which method to call. I can
simply use an "if" statement, but I worry about performance.

David gave you the answer - you need to use a "pointer to member function"
instead of an ordinary function pointer.

If you're worried about performance, the if statement will likely outperform
the pointer to member, unless you have a large number of alternatives. If
it's really just two, then just use the if statement.

-cd


.



Relevant Pages

  • What u mean by this statemnet ?.
    ... where IR is the pointer to structure & func is pointer to fuction. ... func is the member of structure. ... Prev by Date: ...
    (comp.lang.c)
  • Re: Translation-Time Type Information
    ... there are three points of undefined behaviour in the ... point within the same array object. ... functions return the 'value' member of the pointed-to-union, ... pointer is equal to the alignment requirement for that function ...
    (comp.lang.c)
  • Re: Casting of pointer to member functions
    ... cast it back before any usage. ... The example above will compile only if /ymg compiler switch ... the bits that pointer is ... calling a member function through such pointer is ...
    (microsoft.public.vc.language)
  • Re: Problem bei for Anweisung
    ... wenn man ein char-Feld hat. ... — if it has pointer type, it is initialized to a null pointer; ... if it is an aggregate, every member is initialized ... according to these rules; ...
    (de.comp.lang.c)
  • Re: Class members, pointers or not?
    ... > Is it best to declare class member objects as pointers or not pointers? ... using pointer members (and reference members) ...
    (comp.lang.cpp)