c++ - 如何在类中实现可选择的类似命名空间的功能?

标签 c++

我正在为国际象棋引擎创建一个类。该类包含有关每个棋子的位置、允许的移动等信息。该类还允许模拟移动而无需创建新对象。当前的实现如下所示:

// in header file
class ChessGame{
    int base_var1; // base indicates real game value
    int test_var1; // test indicates simulated game value
    ... many other vars of various types

    void makeRealMove(int move); // modifies base values
    void makeTestMove(int move); // modifies test values
}

// in src file
void ChessGame::makeRealMove(int move){
    base_var1 = move; // lots of code in here
}

void ChessGame::makeTestMove(int move){
    test_var1 = move; // identical code here
}

这可行,但 makeRealMove 和 makeTestMove 的代码完全相同,只是将每个 test_var 与适当的 base_var 交换。我想做的是拥有一个函数 makeMove,它可以动态选择要更改的正确类型的变量。这将删除本质上冗余的代码,使调试更容易,等等。如果在类中允许命名空间并且可以有条件地选择,我将执行以下操作:

// in header file
class ChessGame{
    namespace base { int var1; } // plus the other vars
    namespace test { int var1; } // plus the other vars

    void makeMove(int move, bool condition);
}

// in src file
void ChessGame::makeMove(int move, bool real_move){
    if(real_move) { using namespace base; }
    else { using namespace test; }
    var1 = move; // appropriate variable selected
}

不幸的是,命名空间不能嵌套在一个类中,即使它们可以嵌套,我也无法以这种方式在其中两个之间进行选择。那么有没有办法获得这种行为,还是我坚持使用当前的方法?

最佳答案

您可以使用类而不是命名空间:

class ChessGame{
    struct Vars {
      int var1; // plus the other vars
    };
    Vars realGame;
    Vars testGame;

    void makeMove(int move, bool condition);
    void makeMoveImpl(int move, Vars &vars);
};

void ChessGame::makeMove(int move, bool real_move) {
    if (real_move) makeMoveImpl(move, realGame);
    else makeMoveImpl(move, testGame);
}

void ChessGame::makeMoveImpl(int move, Vars &vars) {
    vars.var1 = move; // appropriate variable selected
}

请注意,根据您的设计,将 Vars 设为全局类而不是嵌套类可能更有意义(同时仍将其两个实例存储在 ChessGame 中) . makeMoveImpl 甚至可以成为 Vars 的成员函数,而 ChessGame 将仅充当其中一个或另一个的委托(delegate)者。

关于c++ - 如何在类中实现可选择的类似命名空间的功能?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57621385/

相关文章:

c++ - 类中静态成员的内存分配

c++ - -m32 选项不适用于 gcc 但适用于 g++

c++ - 如何将我自己的函数与 CMake 一起用于 OpenCV

c++ - 如何在 win32 中获取窗口的直接子项(不是任何孙子项)?

c++ - 无法绘制扫雷游戏板

c++ - 当类包含空析构函数时有区别吗

c++ - 使用嵌入式脚本扩展 C++ 应用程序

c++ - 将参数传递给 C++ 中的无操作宏

c++ - 从具有一个已知输入参数和一个未知输入参数的函数构造 std::function

c++ - Qt Creator 中与第 3 方库的链接错误