你可能会使用的是Factory Pattern以及Strategy Pattern和一个合适的接口。沿着线的东西:
struct IPolyRootSolver {
virtual PolyRoot calcRoot(const Polynom& poly) const = 0;
virtual ~IPolyRootSolver() {}
};
class DoublePolyRootSolver : public IPolyRootSolver {
public:
PolyRoot calcRoot(const Polynom& poly) {
// Implementation based on double precision
}
};
class LongDoublePolyRootSolver : public IPolyRootSolver {
public:
PolyRoot calcRoot(const Polynom& poly) {
// Implementation based on long double precision
}
};
class MPFRCPolyRootSolver : public IPolyRootSolver {
public:
PolyRoot calcRoot(const Polynom& poly) {
// Implementation based on MPFRC++ precision
}
};
class RootSolverFactory {
public:
RootSolverFactory(const std::string configFile) {
// Read config file and install a mechanism to watch for changes
}
std::unique_ptr<IPolyRootSolver> getConfiguredPolyRootSolver() {
if(config file contains type = double) {
return make_unique<IPolyRootSolver>(new DoublePolyRootSolver());
}
else if(config file contains type = long double) {
return make_unique<IPolyRootSolver>(new LongDoublePolyRootSolver());
}
else if(config file contains type = MPFRC) {
return make_unique<IPolyRootSolver>(new MPFRCPolyRootSolver());
}
else {
// Handle the default case
}
};
我希望你明白我的意思。
正如在评论中提到,你也可以使用自由站立功能从一个命名空间,而不是上面提到的抽象接口解决方案:
namespace PolyRootDoublePrecision {
PolyRoot calcRoot(const Polynom&);
}
namespace PolyRootLongDoublePrecision {
PolyRoot calcRoot(const Polynom&);
}
namespace PolyRootMPFRCPrecision {
PolyRoot calcRoot(const Polynom&);
}
class RootSolverFactory {
public:
RootSolverFactory(const std::string configFile) {
// Read config file and install a mechanism to watch for changes
}
std::function<PolyRoot (const Polynom&)> getConfiguredPolyRootSolver() {
if(config file contains type = double) {
return std::function<PolyRoot (const Polynom&)>
(PolyRootDoublePrecision::calcRoot);
}
else if(config file contains type = long double) {
return std::function<PolyRoot (const Polynom&)>
(PolyRootLongDoublePrecision::calcRoot);
}
else if(config file contains type = MPFRC) {
return std::function<PolyRoot (const Polynom&)>
(PolyRootMPFRCPrecision::calcRoot);
}
else {
// Handle the default case
}
};
除了使用配置文件,您可以考虑选择使用其他标准作为配置文件的策略。
E.g.就您的情况而言,似乎多项式表达式的复杂性(即子项的数量)对于选择使用的最佳策略起着至关重要的作用。所以你可以写一些代码,如
std::function<PolyRoot (const Polynom&)> getPolyRootSolver(const Polynom& polynom) {
if(polynom.complexity() < 7) {
return std::function<PolyRoot (const Polynom&)>
(PolyRootDoublePrecision::calcRoot);
}
else if(polynom.complexity() >= 7 &&
polynom.complexity() < 50) {
return std::function<PolyRoot (const Polynom&)>
(PolyRootLongDoublePrecision::calcRoot);
}
else if(polynom.complexity() >= 50) {
return std::function<PolyRoot (const Polynom&)>
(PolyRootMPFRCPrecision::calcRoot);
}
};
简单的回答:编号 – NathanOliver
在编译时确定并实例化C++程序中使用的所有变量类型。也许你可以链接一些这些答案,我们可以解释那里做了什么。 –
也许你可以使用if else else if(type ==“double”)double var;否则,如果..... – Sniper