Consider the following template class
class MyClassInterface {
public:
virtual double foo(double) = 0;
}
class MyClass<int P1, int P2, int P3>
: public MyClassInterface {
public:
double foo(double a) {
// complex computation dependent on P1, P2, P3
}
// more methods and fields (dependent on P1, P2, P3)
}
The template parameters P1, P2, P3 are in a restricted range like from 0 to some fixed value n fixed at compile time.
Now I would like to build a “factory” method like
MyClassInterface* Factor(int p1, int p2, int p3) {
return new MyClass<p1,p2,p3>(); // <- how to do this?
}
The question would be how to achieve the construction of the template class when template parameters are only known at runtime. And would the same be possible with template parameters having a very large domain (like a double)? Please consider also, if the possible solution is extendable to using more template parameters.
Here’s what you can do:
Note that this does not even remotely scale to floating point values. It scales only to a known list of discrete values.
I’ve also used this bit of code before to do some template automatic generation:
The compiler produces output that looks like this:
Also, please note that with this method, with 4 variables, each ranging over 13 values, You would cause the compiler to instantiate 28561 copies of this function. If your n was 50, and you still had 4 options, you would have 6250000 functions instantiated. This can make for a SLOW compile.