简体   繁体   中英

Convert Pointer To Member Function To Pointer To Static Function

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);
}

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 .

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

:)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM