简体   繁体   中英

How to convert void (myClass::*)() to void (*)()

I'm currently working on a C++ project on the Unreal Engine and I can't wrap my head around this problem.

class A
{
public: 
    void (* array[10])();

    //Add Function to an array
    void AddFunctionToArray(void(*function)());
};

class B
{
public: 

    A a;

    //Sending a B function to A
    void SendMyFunction();
    void Foo();
};

void B::SendMyFunction()
{
   a.AddFunctionToArray(&B::Foo);
}

I get the error: can't convert void (B::*)() to void (*)()

How can I send a function pointer from one of my class to another?

void (B::*)() is a pointer to a non-static member function, while void (*)() is a pointer to a non-member function. There is no conversion between the two.

Making B::Foo static would fix this problem. However, you will have no access to instance members of B .

Note that using function pointers, member or non-member, is an old style of passing function objects. A more modern way is using std::function objects, which can be constructed from a combination of an object and one of its member functions.

If you're looking to have class A execute a method from an arbitrary class X you can try this:

template <typename UserClass>
void A::FireMethod(UserClass* InUserObject, typename TMemFunPtrType<false, UserClass, void(int)>::Type InFunc)
{
    (InUserObject->*InFunc)(15);
}

In this case we're calling a function with a single int as argument. A class B could do this:

A* a = myAObject;
a->FireMethod(this, &B::MyMethod);

with

void B::MyMethod(int) {}

Hope this helps you! If you want more information, in unreal engine you can look at the AddDynamic macro in Delegate.h

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