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
.