我可以在包含函数地址的向量之类的数组中添加在我的代码中定义的不同函数吗?

Can I add a different function that is defined in my code in a vector like arrays that include function adress?

在这段代码中,有 6 个不同的函数。他们创建了 6 个不同的棋盘来玩游戏。但我不想创建具有 if 条件的板,我想创建一个包含函数地址的 vector。例如,如果用户想创建棋盘 4 来玩游戏,我想这样创建棋盘:

vector<vector<cell>> a = function_array[3];

cell 是我声明的 enum 类型。

我可以这样做吗?有人可以帮助我吗?

vector<vector<cell>> first_table();
vector<vector<cell>> second_table();
vector<vector<cell>> third_table();
vector<vector<cell>> fourth_table();
vector<vector<cell>> fifth_table();
vector<vector<cell>> sixth_table();
    
int main()
{
    int chose,board_type;
    vector<vector<vector<cell>>> functions;

    functions.push_back(first_table());
    functions.push_back(second_table());
    functions.push_back(third_table()); //in here I create all boards and print which one the user wants
    functions.push_back(fourth_table()); //but I don't want to do this, I want just create the board the user wants
    functions.push_back(fifth_table());
    functions.push_back(sixth_table());

    vector<vector<cell>> b = functions[board_type-1];
    print_game(b);
    b = functions[0];
    cout << "welcomw Game" << endl;
    cout << "Please chose board type" << endl;
    cin >> board_type;
    int game_type;
    cout << "1.Personal game " << endl << "Computer game" << endl;
    cin >> game_type;
    string input;
    cout << "Please enter move direction" << endl;
    cin >> input;
}

您要找的是std::function

在您的情况下,您将为不带参数的函数创建 std::function<> 的向量,并且 return 和 vector<vector<cell>>.

#include <functional>
#include <vector>

struct cell {};

//type aliases make code a lot more readable!
using board = std::vector<std::vector<cell>>;

board first_table();
board second_table();
board third_table();
board fourth_table();
board fifth_table();
board sixth_table();

int main() {
  std::vector<std::function<board()>> functions;

  functions.push_back(first_table);
  // etc...

  board b = functions[board_type-1]();
}