Consider the following example:
class MyContainer {
std::vector<void *> v;
public:
void Put(void *x) { v.push_back(x);}
void* Get(int index) { return v[index];}
};
void Work (MyContainer& c) {
// cast_to_type(c.Get(0));
}
int main() {
int x = 1;
double y = 2.0;
MyContainer c;
c.Put(&x);
c.Put(&y);
Work(c);
return 0;
}
Assume that function Work knows nothing about the objects to which vector pointers point to. Also assume that inheritance is not an option and that types of the pointed objects can be arbitrary (there can be infinite number of types).
Is it possible to deduce the type using only the void pointer returned by MyContainer::Get function? Can this be done using any combination of casts, templates and typeid operator?
No,
void*s have absolutely no information associated with them whatsoever, and when you cast a pointer to avoid*, you lose the type completely. You’ll have to find another way to store different types in the same container, such as with inheritance.You could also do something like this:
But I don’t know how much help that would be without knowing what you are trying to do. You might have to resort to something a little more advanced like
boost::any.