0

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

4

2 回答 2

2

C++ 是强类型的。表达式(expr)始终具有相同的静态类型。如果静态类型是动态类型的基类型,它可能具有可变动态类型。这显然不是这里的情况。

因此,唯一的解决方案是编写两个演员表:

if (flag)
  std::cout << * static_cast<int*>(ptr);
else
  std::cout << * static_cast<double*>(ptr);

这两个表达式都有一个静态确定的类型,在运行时您选择对ptr.

于 2013-07-29T14:32:37.837 回答
1

C 和 C++ 不会“存储”什么类型的东西——编译器知道它,但是一旦代码被编译,这些信息就会被丢弃。它来自您编写的表达式 - 当然 avoid只是一种特殊类型,表示“这没有类型”。

int如果内容是或,您将需要以某种方式自行跟踪double。如果你不能做到这一点,那么它就被“破坏”了,无法做到。

于 2013-07-29T14:43:51.357 回答