I have a routine in the main.cpp where user will specify which mode to execute in the program. Once the mode is specified, the corresponding block will be executed - first downcast the parent solver to the child solver and call the associated solve
method in the child class.
std::unique_ptr<SudokuSolver> solver;
if (mode == MODES::SEQUENTIAL_BACKTRACKING)
{
solver = std::make_unique<SudokuSolver_SequentialBacktracking>();
SudokuSolver_SequentialBacktracking* child_solver = dynamic_cast<SudokuSolver_SequentialBacktracking*>(solver.get());
child_solver->solve(board);
}
else if (mode == MODES::SEQUENTIAL_BRUTEFORCE)
{
solver = std::make_unique<SudokuSolver_SequentialBruteForce>();
SudokuSolver_SequentialBruteForce* child_solver = dynamic_cast<SudokuSolver_SequentialBruteForce*>(solver.get());
child_solver->solve(board);
}
else if (mode == MODES::PARALLEL_BRUTEFORCE)
{
int NUM_THREADS = (argc >= 5) ? std::stoi(argv[4]) : 2;
omp_set_num_threads(NUM_THREADS);
#pragma omp parallel
{
#pragma omp single nowait
{
solver = std::make_unique<SudokuSolver_ParallelBruteForce>();
SudokuSolver_ParallelBruteForce* child_solver = dynamic_cast<SudokuSolver_ParallelBruteForce*>(solver.get());
child_solver->solve(board);
}
}
}
else if (mode == MODES::SEQUENTIAL_DANCINGLINKS)
{
solver = std::make_unique<SudokuSolver_SequentialDLX>(board);
SudokuSolver_SequentialDLX* child_solver = dynamic_cast<SudokuSolver_SequentialDLX*>(solver.get());
child_solver->solve();
}
else if (mode == MODES::PARALLEL_DANCINGLINKS)
{
int NUM_THREADS = (argc >= 5) ? std::stoi(argv[4]) : 2;
omp_set_num_threads(NUM_THREADS);
#pragma omp parallel
{
#pragma omp single
{
solver = std::make_unique<SudokuSolver_ParallelDLX>(board);
SudokuSolver_ParallelDLX* child_solver = dynamic_cast<SudokuSolver_ParallelDLX*>(solver.get());
child_solver->solve();
}
}
}
I found it's kinda duplicates of code so I want to templatize them to something like:
template <typename T>
void downCastandSolve(std::unique_ptr<SudokuSolver> solver, SudokuBoard& board)
{
solver = std::make_unique<T>(board);
T* child_solver = dynamic_cast<T*>(solver.get());
child_solver->solve();
}
However, I got the following error message:
error: use of deleted function ‘std::unique_ptr<_Tp, _Dp>::unique_ptr(const std::unique_ptr<_Tp, _Dp>&) [with _Tp = SudokuSolver; _Dp = std::default_delete<SudokuSolver>]’
Not sure how to properly templatize the portions of code. Hope someone could help!