How do I get the template type of a given element at runtime in C++? -
i'm designing simple array class capability of holding type of object, vector can hold multiple types of data in 1 object. (this learning purposes.)
i have empty base class called container:
class container {};  and templatized subclass called object:
template <class t> class object : public container { t& object; public: object(t& obj = nullptr) : object(obj) {} };  i have array class holds vector of pointers containers use hold objects:
class array { std::vector<container *> vec; public: template <class t> void add_element(const t&); auto get_element(int); };  add_element stores elements objects , puts them vec:
template <class t> void array::add_element(const t& element) { vec.push_back(new object<t>(element)); }  get_element removes element it's object , passes caller. problem lies. in order remove element object, need know type of object is:
auto array::get_element(int i) { return (object</* ??? */> *)vec[i])->object; }  is there way me find out sort of object i'm storing?
edit: since people claiming not possible, how this. there way of storing type information inside of class? (i know can in ruby). if that, store return type of get_element in each object.
i thinking along lines of template get_element.
template <class t> t& array::get_element(int i, t &t) {     object<t> *o = dynamic_cast<object<t> *>(vec[i]);     if (o == 0) throw std::invalid_argument;     return t = o->object; } array arr; double f; int c; arr.get_element(0, f); arr.get_element(1, c);  but alternatively, use this:
template <class t> t& array::get_element(int i) { object<t> *o = dynamic_cast<object<t> *>(vec[i]); if (o == 0) throw std::invalid_argument; return o->object; } f = arr.get_element<double>(0); c = arr.get_element<int>(1);  
Comments
Post a Comment