Reputation: 230
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?
Upvotes: 3
Views: 4071
Reputation: 75130
No, void*
s have absolutely no information associated with them whatsoever, and when you cast a pointer to a void*
, 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:
class MyContainer {
struct cont {
void* ptr;
type_info* ti; // pointer, not reference, so this struct can be copied
};
std::vector<cont> v;
public:
template<typename T>
void Put(T* x) {
v.push_back({ x, &typeid(T) });
}
// do whatever you want with Get using *v[x].ti
};
int x = 1;
double y = 2.0;
MyContainer c;
c.Put(&x);
c.Put(&y);
Work(c);
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
.
Upvotes: 9