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);
}
}
Well, you certainly can't do that. You'll have to make A derive from another class, for example:
template<typename T>
class A : public B {
public:
A(T v){var = v};
~A(){};
T var;
}
int main(){
B* object;
if(/* something*/)
object = new A<float>(0.2f);
else{
object = new A<int>(3);
}
}
The easiest way to do this is to use another function.
template<typename T> void other_stuff(A<T>* object) {
// use T here
}
int main() {
if (condition)
other_stuff(new A<float>(0.2f));
else
other_stuff(new A<int>(3));
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With