你可能會使用的是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