チェスエンジンのクラスを作成しています。このクラスには、各ピースの場所、許可される移動などに関する情報が含まれています。このクラスでは、新しいオブジェクトを作成しなくても、移動をシミュレートすることもできます。現在の実装は次のようになります。
// 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と交換するだけです。私がやりたいのは、変更する適切なタイプの変数を動的に選択できる1つの関数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つから選択することはできませんでした。それで、この種の振る舞いを得る方法はありますか、それとも私は現在のアプローチに固執していますか?
名前空間の代わりにクラスを使用できます。
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
、ネストされたクラスではなくグローバルクラスを作成することが理にかなっている場合があることに注意してください(その中に2つのインスタンスを格納しますChessGame
)。makeMoveImpl
その後、さえのメンバ関数になる可能性Vars
と、ChessGame
ちょうど1または他の委任者として役立つであろう。
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加