简体   繁体   English

将指针转换为成员函数将指针转换为静态函数

[英]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: 您可以将std::bind到相关类的实例:

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

This binds the member function Class::func to a . 此结合成员函数Class::funca 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: 另外,您可以使用std::mem_fn来轻松更改被调用的对象,并提供所需的语法:

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. 并非在两种情况下func1func2实际上都不是函数指针,但它们的行为确实像它们。 The types returned from std::bind and std::mem_fn are implementation defined. std::bindstd::mem_fn返回的类型是实现定义的。 They are both, however, convertable to a std::function . 它们都可以转换为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 解决了

:) :)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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