如何在类中实现可选的类似于名称空间的功能?

时间:2019-08-23 07:09:24

标签: 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
}

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

2 个答案:

答案 0 :(得分:7)

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

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则可以充当一个或另一个的委托人。

答案 1 :(得分:1)

class ChessGame{
    std::array<int, 2> var; // var[0] == real game value, var[1]== simulated game value
    //... many other vars of various types
    void makeRealMove(int move){makeMove(move,false);};
    void makeTestMove(int move){makeMove(move,true);};
    void makeMove(int move, bool test){
        var[test]= move;
        // lots of code in here
    };
};
相关问题