quote:Original post by Wyrframe
I''m not making the ZArray of type ''T'', I''m making it an int, char, or float, depending on some input.
Then you have a fundamental misunderstanding of how templates work. They provide what is known as parametric polymorphism, which is despatched in C++ purely at compile time. That is, you cannot instantiate a templated type at run time. Each instantiation of a templated class is an entirely different entity to any other, unless you do something else to relate them. For example, if you have the templated class:
template<typename T>class SomeClass{public: T getValue() const; void setValue( T value );private: T value_;};
Then, if you instantiate this template as:
SomeClass<int> sc_i;SomeClass<double> sc_d;
You have created two classes with no inter-relationship other than they were created from the same template. They cannot be used interchangeably as they stand. If you do something like:
SomeClass *p_sc1, *p_sc2;p_sc1 = new SomeClass<int>;p_sc2 = new SomeClass<double>;
That is illegal C++ code, since you have not instantiated the SomeClass pointer with a type. Visual C++ accepts and compiles this, but that doesn''t make it correct. It is gibberish.
If you really want to achieve runtime polymorphism between these types then, as sjelkjd mentions, the mechanism to do so is the same as with non-templated classes: i.e. derive from a common root. For example:
class Base{//...};template<typename T>class SomeClass : public Base{public: T getValue() const; void setValue( T value );private: T value_;};
Now you can have your pointer-to-indeterminate-type that you are trying to achieve:
Base *p_sc1, *p_sc2;p_sc1 = new SomeClass<int>;p_sc2 = new SomeClass<double>;// ...do stuff with the objects...delete p_sc1;delete p_sc2;
Note that the two template instantiations here will be carried out *at compile time*, that is two class definitions will be created. The only thing that gets deferred until runtime is the creation of instances of those classes.
Whether this is a good design for what you are trying to do is open to debate. In fact, don''t take the example I''ve provided you with as something I''d necessarily endorse, as I can think of several potential issues. I''m just demonstrating the mechanisms you seem to be confused with.
--
1st law of programming: Any given program, when running, is obsolete.