Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

An Array of Function Pointers in C++

I'm trying to figure out on how can I make an array of pointers to functions that are inside a class. Where an element in an array represents a unique function.

Tiles.h code:

class tiles: public box
{
    public:
        void north2east(float trans_x, float trans_y);
        void north2west(float trans_x, float trans_y);
        void south2east(float trans_x, float trans_y);
        void south2west(float trans_x, float trans_y);
};

Tiles.cpp code:

void tiles::north2east(float trans_x, float trans_y); { }
void tiles::north2west(float trans_x, float trans_y); { }
void tiles::south2east(float trans_x, float trans_y); { }
void tiles::south2west(float trans_x, float trans_y); { }

I've heard that you can do it by adding the following in the Tiles.cpp file:

typedef void (*FUNC_ARRAY) (float trans_x, float trans_y);
FUNC_ARRAY functions[] = {
    tiles::north2east,
    tiles::north2west,
    tiles::south2east,
    tiles::south2west
}

But this gives me the following error:

a value of type "void (tiles::*)(float trans_x, float trans_y)" cannot be used to initialize an entity of type "FUNC_ARRAY"

Tips and suggestions on solving the code are welcome!

like image 571
VesmirPendel Avatar asked Jun 13 '26 18:06

VesmirPendel


1 Answers

Just change your typedef to:

typedef void (tiles::*FUNC_ARRAY) (float trans_x, float trans_y);
//            ^^^^^^^

Your current typedef can only be used for regular functions and static member functions. What you need there is a pointer to a member function.

like image 175
Shoe Avatar answered Jun 16 '26 06:06

Shoe