'How Should I Define an Array of Pointers to Functions in C++?
I'm trying to make an array of functions so I can call functions from the array with an index. I can't seem to figure out the parentheses, asterisks and brackets to create this array of functions. Here is what I have:
void Game::getPawnMoves(int position, bool color, Move ** moveList) {
...
}
typedef void (*GetMoveFunction) (int, bool, Move **);
void Game::getLegalMoves(Move ** moveList) {
GetMoveFunction functions[] =
{
getPawnMoves,
getKnightMoves,
getBishopMoves,
getRookMoves,
getQueenMoves,
getKingMoves
};
...
}
All of the getPawnMoves, getKnightMoves, and the rest all have the same arguments and all return void. Move is just a struct with two chars and an enum. In this case, if you'd like to try compiling it, you could replace Move ** with int **.
The error I'm getting when I compile is:
Game.cpp:443:5: error: cannot convert ‘Game::getPawnMoves’ from type
‘void (Game::)(int, bool, Move**) {aka void (Game::)(int, bool, Move_t**)}’ to
type ‘GetMoveFunction {aka void (*)(int, bool, Move_t**)}’
So for some reason the compiler thinks that GetMoveFunction is void * instead of void, but if I change the typedef to
typedef void (GetMoveFunction) (int, bool, Move **);
I get the error:
Game.cpp:435:28: error: declaration of ‘functions’ as array of functions
GetMoveFunction functions[] =
I'm honestly super stuck on this one. Thanks so much for your help!
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
