Re: Variable to take type of templated class with variable template parameter
On Oct 29, 8:08 am, David Sanders <dpsand...@gmail.com> wrote:
I have a class depending on a template parameter:
template<int n>
class MyClass {
};
I want the template parameter to be chosen according to a variable,
e.g.
switch (method) {
case 1:
pointer = new MyClass<1>;
break;
case 2:
pointer = new MyClass<2>;
break;
The question is: what type should 'pointer' be?
The only thing that occurs to me is to inherit MyClass from a non-
templated abstract base class:
class BaseClass {
};
template<int n>
class MyClass : public BaseClass {
};
and then define
BaseClass* pointer;
This seems to work,
It's also about the only thing that will work. Different
instantiations of MyClass are unrelated classes; you have to
explicitly relate them.
but it requires me to define dummy pure virtual versions in
BaseClass of all the methods in MyClass, which seems like
something that should be able to happen automatically.
Not really. What should this "implicitly defined" base class
look like if there are specializations of your template?
Templates and runtime polymorphism are two very different
things. If you want runtime polymorphism, you must follow the
rules of runtime polymorphism (even if you use templates in the
implementation of the derived types).
The basic reason for this is that runtime polymorphism takes
place in a different environment than template instantiation.
Templates can get away with duck typing because if you
instantiate over a type which doesn't meet the contract, the
compiler will complain, and the error doesn't go any further.
Use duck typing a runtime (a la Smalltalk or Lisp), and you risk
type errors at runtime---require a common base class and
explicit derivation, and the compiler can catch most of these
errors.
Is there a simpler / better solution to this problem?
[The other question is how to make the switch statement
automatic, but that I guess one does with some kind of factory
method?]
More or less (although I usually use factory objects). Just put
the address of the function/object in a map, indexed by the key.
--
James Kanze (GABI Software) email:james.kanze@gmail.com
Conseils en informatique orient=E9e objet/
Beratung in objektorientierter Datenverarbeitung
9 place S=E9mard, 78210 St.-Cyr-l'=C9cole, France, +33 (0)1 30 23 00 34