Want declare variable smth like TCombGenerate<n> *gen;
and do
gen=new TCombGenerate<m>(...);
and call gen->generate without any casting. Is it possible wnen m isn't known at compile time?
You can't do that because TCombGenerate<n> and TCombGenerate<m> are different types if n != m. A possible work around is to have all TCombGenerate inherit from a base class that has a virtual function generate();
1 2 3 4 5 6 7 8 9 10 11 12 13
class CombGenerateBase
{
public:
virtualvoid generate() = 0;
};
template <int n>
class TCombGenerate : public CombGenerateBase
{
...
void generate();
...
};
1 2 3
CombGenerateBase *gen;
gen = new TCombGenerate<m>(...);
gen->generate();
No, you can't instantiate a template at run-time. The reason behind this is that templates are not complete types until all template information is given. The compiler needs all the template information to determine just how much memory a template-class needs. This is not practical during run-time. Template parameters are constant-expressions, which means the value of the expression needs to be deduced before run-time. Therefore, non-constant variables are not suitable as template actual parameters.
Oh sorry. I didn't pay attention to that the template argument was not a type. In that case I don't think this work around is suitable. Why not use a normal class and pass the int value as argument to the constructor?