The basic idea is that I have a “family” of classes that all do the same identical thing, but in a slightly different way. This “family” is used in a “high performance” loop, so speed is of the essence. Further, the specific family is specified by a configuration file…
The problem is that there is tremendous code repetition in the main function here. Is there a better way to structure this so I don’t have to write HP<objx> test and test.loop(bobloblaw) three times? (In practice, this chunk of code is many more lines than 2…)
class obj1 {
public:
double f(double x) const { return 1.; }
};
class obj2 {
public:
double f(double x) const { return x; }
};
class obj3 {
public:
double f(double x) const { return x*x; }
};
template <class O>
class HP {
private:
O obj;
public:
double loop(const vector<double>& x) {
double s = 0.;
for (auto i : x) s += obj.f(i);
return s;
}
};
int main() {
string config = "bob";
double result = 0;
vector<double> bobloblaw;
/* Read configuration file to determine which object to use. */
if (config == "obj1") {
HP<obj1> test;
result = test.loop(bobloblaw);
} else if (config == "obj2") {
HP<obj2> test;
result = test.loop(bobloblaw);
} else if (config == "obj3") {
HP<obj3> test;
result = test.loop(bobloblaw);
}
return result;
}
The following is untested, but should work:
Note that the only addition is a base class for
HP<>and a map which replaces theif/elselogic of your code.