Alexandre Blanchet
Alexandre Blanchet

Reputation: 107

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?

Upvotes: 2

Views: 1667

Answers (2)

Bas in het Veld
Bas in het Veld

Reputation: 1312

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

Upvotes: 0

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726599

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.

Upvotes: 4

Related Questions