How do I get the template type of a given element at runtime in C++?
c++, polymorphism, templates
Solution
I was thinking something along the lines of this template for your `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, you could 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);
Problem
I'm designing a simple `Array` class with the capability of holding any type of object, like a vector that can hold multiple types of data in one object. (This is for learning purposes.) I have an empty base class called `Container`: ``` class Container {}; ``` And a templatized subclass called `Object`: ``` template <class T> class Object : public Container { T& object; public: Object(T& obj = nullptr) : object(obj) {} }; ``` I have an `Array` class which holds a `vector` of pointers to `Container`s which I use to hold `Object`s: ``` class Array { std::vector<Container *> vec; public: template <class T> void add_element(const T&); auto get_element(int); }; ``` `add_element` stores elements into `Object`s and puts them into `vec`: ``` template <class T> void Array::add_element(const T& element) { vec.push_back(new Object<T>(element)); } ``` `get_element` removes the element from it's `Object` and passes it back to the caller. This is where my problem lies. In order to remove the element from the `Object`, I need to know what type of `Object` it is: ``` auto Array::get_element(int i) { return (Object</* ??? */> *)vec[i])->object; } ``` Is there some way for me to find out what sort of object I'm storing? Edit: since people are claiming that this is not possible, how about this. Is there some way of actually storing type information inside of a class? (I know you can do that in ruby). If I could do that, I could store the return type of `get_element` in each `Object`.