Hi,
I wonder if I can use template with polymorphism. The problem is that it seems impossible to define a pointer to an uninstantiated template. For instance, here is a toy example,
Code:
#include <iostream>
#include <cstring>
using namespace std;
template<class T>
class A {
public:
T a;
virtual void f(){ cout<< "A"<< endl;}
};
template<class T>
class B: public A<T> {
public:
void f(){ cout<< "B"<< endl;}
};
template<class T>
class C: public A<T> {
public:
void f(){ cout<< "C"<< endl;}
};
int main(int argc, char **argv){
A * ptr; // error: missing template arguments before ‘*’ token
if (strcmp(const_cast<const char*>(argv[1]), "B") == 0){
if (strcmp(const_cast<const char*>(argv[2]), "int") == 0) ptr = new B<int>;
else if(strcmp(const_cast<const char*>(argv[2]), "float") == 0) ptr = new B<float>;
} else if(strcmp(const_cast<const char*>(argv[1]), "C") == 0){
if (strcmp(const_cast<const char*>(argv[2]), "int") == 0) ptr = new C<int>;
else if (strcmp(const_cast<const char*>(argv[2]), "float") == 0) ptr = new C<float>;
}
ptr->f();
return 0;
}
Is there any possible way to use template and polymorphism?
THanks and regards!