2

How do I convert a member function pointer to a static function?

Here is my code:

class ClassA
{
public:
    int n;
    void func();
};
void ClassA::func()
{
    n = 89;
}

class ClassB
{
public:
    float f1;
    float f2;
    void func(float f);
};
void ClassB::func( float f )
{
    f1 += f;
    f2 += f;
}


int main (int argc, char *argv[]) 
{
    ClassA* a = new ClassA;
    ClassB* b = new ClassB;

    //PROBLEM IS HERE
    void (* pf_func1)(void*) = ClassA.func;
    void (* pf_func2)(void*, float) = ClassB.func;


    pf_func1(a);
    pf_func2(b, 10);
}
1
  • There are various mistakes in that code snippet, missing ; after classes declarations, using new instead of just putting the variable on the stack, using ClassA.func instead of ClassA::func... I suggest you start with learning about C++ from a good book or university course. Commented Feb 23, 2013 at 14:13

2 Answers 2

2

You could std::bind it to an instance of the relevant class:

auto func1 = std::bind(&ClassA::func, a);
func1();

This binds the member function Class::func to a. And similarly:

auto func2 = std::bind(&ClassB::func, b, std::placeholders::_1);
func2(10.0f);

Alternatively, you can use std::mem_fn to allow you to easily change the object that it is called on, providing the syntax that you asked for:

auto func1 = std::mem_fn(&ClassA::func);
func1(a);
auto func2 = std::mem_fn(&ClassB::func);
func2(b, 10.0f);

Not that in both cases func1 and func2 aren't actually function pointers, but they do behave like them. The types returned from std::bind and std::mem_fn are implementation defined. They are both, however, convertable to a std::function.

Sign up to request clarification or add additional context in comments.

3 Comments

You're incredibly fast. I was just starting typing.
Note: std::bind is a C++11 feature; if your compiler is too old for that you can use boost::bind instead.
@UFNHGGI Then perhaps use boost::bind and BOOST_AUTO.
-1
void(ClassA::*pf1)() = &ClassA::func;
void(ClassB::*pf2)(float) = &ClassB::func;
void (__thiscall * pf_func1)(void*) = (void (__thiscall *)(void*)) ((void*&)pf1);
void (__thiscall * pf_func2)(void*, float) = (void (__thiscall *)(void*, float)) ((void*&)pf2);

SOLVED

:)

3 Comments

This is undefined behavior. It may stop working at any time. For example, if you use multiple inheritance.
This is absolutely true. Why the negative rating :((
Um, because it's the wrong answer, and if somebody else tries it, their code may crash?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.