I've got a class template, and I need to declare an object of that class, without defining the type parameters, so that I can define them conditionally later, e.g.:
template<typename T>
class A{
public:
A(T v){var = v};
~A(){};
T var;
}
int main(){
A<>* object; // Or sometihng along these lines...?
if(/* something*/)
object = new A<float>(0.2f);
else{
object = new A<int>(3);
}
}
Templates are expanded at compile-time, so your problem is really just the same as the following:
Hopefully if you saw the above code, you'd think (as well as "maybe I should be using templates") "I am going to need a common base class for this, or else I'll refactor".
When you generate the two types at compile-time using a class template, this conclusion is the same.
You can use void pointer while create object of class A
Look at Following code sample :
Well, you certainly can't do that. You'll have to make A derive from another class, for example:
The easiest way to do this is to use another function.
This maintains all type information and does not depend on inheritance. The disadvantage of inheritance is that T cannot appear in any function interfaces, but with this situation it can.