Reputation: 30273
Is it possible to define a pointer to an unknown numeric type, say int
or double
, that always returns a specific type, say double
, on dereferencing?
I started doing this,
int a = 7;
double b = 3.14;
void* c = static_cast<void*>(&a);
void* d = static_cast<void*>(&b);
double e = *(static_cast<double*>(c));
double f = *(static_cast<double*>(d));
but of course, casting an int*
to a double*
is just going to produce gibberish for e
since we'd be reinterpreting the internal bits for an int
as if they were in double
format.
I tried in earnest to answer in advance why I'd need to do this, since certainly there must be a better design option, but the explanation got wordy. In short, it has to do with legacy code, some parts of which I can't modify, and since we're planning on rewriting the affected components anyway, I'm currently investigating whether a workaround is possible.
In case my watered-down version is too watered down, here's one more level of detail. I'm working with a method that must return a double
, by dereferencing what used to be a void
pointer to a double
(in shared memory), but now may point to an int
too. There is a "hook" that's invoked when the pointer is set to point to another location, at which point it's known whether it's going to point to a double
or an int
. So the only thing I can think of doing, is storing the type (or setting a flag) in a member variable during that hook, and casting to a pointer of that type before dereferencing.
But I was hoping someone would know a handy trick or technique I may have missed. Some other way of storing pointers or organizing types so that I won't have to modify the hook at all (I'd really like to avoid doing that, for other, cumbersome-to-explain reasons).
Upvotes: 0
Views: 60
Reputation: 129374
C and C++ doesn't "store" what type something is - it is known by the compiler, but once the code has been compiled, this information is discarded. It comes out of the expression that you write - and of course a void
is just a special type to indicate "this has no type".
You will need to track, yourself, somehow if the content is int
or double
. If you can't do that, then it's "busted", can't be done.
Upvotes: 1
Reputation: 179907
C++ is strongly typed. An expression (expr)
always has the same static type. It may have a variable dynamic type, if the static type is a base type of the dynamic type. That's obviously not the case here.
So, the only solution is to write both casts:
if (flag)
std::cout << * static_cast<int*>(ptr);
else
std::cout << * static_cast<double*>(ptr);
Both expressions have a statically-determined type, and at runtime you choose the expression (and thus the type) which is correct for the data in ptr
.
Upvotes: 2