我正在尝试根据某些变量的状态实例化不同类型的对象。我认为执行此操作的官方方法是使用称为工厂方法的方法;但这超出了我目前的技能水平,所以我正在寻找一种快速而肮脏的方法来做到这一点。
在下面的代码中,应根据
solver
变量的状态实例化 solverType
对象。
#include <appropriateHeaders.h>
int main() {
// pseudocode representing the solverType being set
std::string solverType;
read_solverType_from_file(solverType);
// actual code from my program; though in reality there are about 12 options
if (solverType == "SimplicialLLT") {
Eigen::SimplicialLLT<Eigen::SparseMatrix<double>> solver;
} else if (solverType == "SimpliciaLDLT") {
Eigen::SimplicialLDLT<Eigen::SparseMatrix<double>> solver;
}
return 0;
}
上述代码的问题当然是
solver
变量在 if 块末尾超出了范围。那么有没有办法实现这个目标(不诉诸工厂方法)?
一个选项可能只是写出十二个不同的选项,然后注释掉除我想使用的选项之外的所有选项。但如果我可以使用逻辑语句来做到这一点,我更愿意!
谢谢。
最简单的解决方案可能是使用模板化函数:
template<typename SOLVER>
void solve(SOLVER solver) {
//...
}
int main() {
// pseudocode representing the solverType being set
std::string solverType;
read_solverType_from_file(solverType);
// actual code from my program; though in reality there are about 12 options
if (solverType == "SimplicialLLT") {
Eigen::SimplicialLLT<Eigen::SparseMatrix<double>> solver;
solve(solver);
} else if (solverType == "SimpliciaLDLT") {
Eigen::SimplicialLDLT<Eigen::SparseMatrix<double>> solver;
solve(solver);
}
return 0;
}