samedi 29 juillet 2017

How to access member funtions of a derived Template class if we have a base* class

I have a template class derived from a base class.

Also in main, I have a vector container which contains various types of the derived class. Without knowing the type of the Derived class, how can I access its member functions in main?

Template specializition could be a good solution to this problem. But, how can I do that?

class Base{ // The base class of a template class
public:
    Base(){}
    virtual ~Base(){}
};

template <typename T>
class Derived : public Base{ // The template class,
                             // derived from the base class.
    T data;
public:
     Derived(){}
    ~Derived(){}

       T  get()       { return data; }
     void set( T val) { data = val;  }
};

int main() {

    vector <Base*> myObject;
    // I have different types of Derived class
    // in a vector conteiner.

    Derived<int>  *D1=new Derived<int>;
    Derived<float>*D2=new Derived<float>;
    Derived<char> *D3=new Derived<char>;

    myObject.push_back(D1);
    myObject.push_back(D2);
    myObject.push_back(D3);

    for (int i=0;i<myObject.size();i++){
         // myObject[i]->set(4);  Error! : myObject is a vector of <Base*>
         // myObject[i]->get();   Error! : not a vector of <Derived*>
    }

  return 0;
}

Aucun commentaire:

Enregistrer un commentaire