variable of template class

Have
1
2
3
4
5
6
7
template <int n>
class TCombGenerate 
{
  ...
  viod generate();
  ...
};


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?
Last edited on
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:
	virtual void generate() = 0;
};

template <int n>
class TCombGenerate : public CombGenerateBase
{
	...
	void generate();
	...
};


1
2
3
CombGenerateBase *gen;
gen = new TCombGenerate<m>(...);
gen->generate();
Last edited on
it's not complete work around:
for line
 
gen = new TCombGenerate<m>(...);


obtain:

‘m’ cannot appear in a constant-expression


is there in c++ mechanism of REAL runtime instantiation?
Last edited on
closed account (zb0S216C)
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.

Wazzak
Last edited on
clear, useless stuff :(
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?
Topic archived. No new replies allowed.