[모던C++입문] 6.4 서브 타입별 동적 선택
- 📕 Book/모던C++입문
- 2021. 8. 1.
6.4 서브 타입별 동적 선택
- switch문을 이용해 프로그램을 동적으로 선택하도록 구현해보자.
class matrix {};
class vector {};
void cg(const matrix& A, const vector& b, vector& x);
void bicg(const matrix& A, const vector& b, vector& x);
struct solver
{
virtual void operator()(const matrix& A, const vector& b, vector& x)= 0;
virtual ~solver() {}
};
// 잠재적으로 템플릿화 됨
struct cg_solver : solver
{
virtual void operator()(const matrix& A, const vector& b, vector& x) override
{ cg(A, b, x); }
};
struct bicg_solver : solver
{
virtual void operator()(const matrix& A, const vector& b, vector& x) override
{ bicg(A, b, x); }
};
int main (int argc, char* argv[])
{
using namespace std;
matrix A;
vector b, x;
int solver_choice= argc >= 2 ? std::atoi(argv[1]) : 0;
//일반적인 처리
//복잡도에따라 확장하기 어렵다.
switch (solver_choice) {
case 0: cg(A, b, x); break;
case 1: bicg(A, b, x); break;
}
// 팩토리 패턴 (C++11)
unique_ptr<solver> my_solver;
switch (solver_choice) {
case 0: my_solver= unique_ptr<cg_solver>(new cg_solver); break;
case 1: my_solver= unique_ptr<bicg_solver>(new bicg_solver); break;
}
// 팩토리 패턴 2
//make_unique를 사용 (C++14)
unique_ptr<solver> my_solver;
switch (solver_choice) {
case 0: my_solver= make_unique<cg_solver>(); break;
case 1: my_solver= make_unique<bicg_solver>(); break;
}
(*my_solver)(A, b, x);
}
반응형