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).