Re: Dynamic Templates
pfultz2 schrieb:
I was wondering, first if this was possible with templates, say i have
a class like this:
template<class T, int N>
class foo : public foo_base
{
};
can instantiate this class like using a runtime integer like this:
int i = calculateSize();
foo_base * var = new foo<int, N>();
Unfortunately, C++ doesn't allow that. If it would, then either the
instantiation and hence compilation would have to happen at run-time -
which is not supported by the C++ execution model - or the compiler
would have to generate code for each possible value of "i" - which would
be quite a lot of classes for integers.
and if thats possible, could i instantiate it the class using some
runtime type, perhaps something like this:
class c = getType();
foo_base * var = new foo<c, 0>();
Neither, same problem. It must be known at *compile time* which
templates are to be instantiated.
perhaps it could be done, but not in this simple way.
The usual solution is to have a big switch-case with all the values that
you need to handle:
switch(calculateSize()) {
case 1:
var = new foo<XXX,1>();
break;
case 2:
var = new foo<XXX,2>();
break;
....
of course, this is only practical if the number of possibilities is
limited. Otherwise, you would not only create a very long and unreadable
switch-case, you would also create a lot of code. Your binary would be
extremely long.
So long,
Thomas
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]