a concerned citizen a concerned citizen - 11 days ago 5
C++ Question

Choose variable type at runtime through config file

I have seen answers that deal with choosing a variable type, dynamically, at runtime(this, and this, and links from there on), but, even if some may go a bit over my head (fairly new to C++), is there a way to read the variable type from a config file and use it during runtime?

For example, the config may have

type=double
as a line, and can be changed to
type=long double
through the settings of the program, and use that variable type without restarting the application.




I need to calculate the roots of some polynomials. Some, even of they have small orders, need large precision, and if they get to high orders, they need even greater. Still, I can do away with
double
or
long double
for small enough numbers, but as I get higher, I need MPFRC++ (which is what I am sing, currently). I'd like to avoid the slowing down (even if it's not that noticeable for smaller orders) bu being able to use high precision only when needed.

Answer

What you may be could use is a Factory Pattern along with the Strategy Pattern and an appropriate interface. Something along the lines:

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
         }
};

I hope you get what I mean.