無効なポインターで非仮想メンバー関数を呼び出すことができると、オブジェクトに関連付けられた情報をポインター自体にエンコードすることもできます。例えば:
#include <iostream>
class MagicInteger {
public:
static MagicInteger* fromInt (int x) {
return reinterpret_cast<MagicInteger*>(x);
}
int getValue() {
return static_cast<int>(reinterpret_cast<intptr_t>(this));
}
private:
// forbid messing around
MagicInteger ();
MagicInteger (MagicInteger&);
MagicInteger& operator=(const MagicInteger&);
};
int main (void) {
MagicInteger* i = MagicInteger::fromInt(6);
std::cout << "Value is " << i->getValue() << std::endl;
return 0;
}
これは、タグ付きポインター、つまり、ポインターに関するメタ情報を含むポインターを実装するためにも使用できます。
これらの2つのイディオムは、GoogleChromeのjavascriptVMV8で31ビット整数を表すために使用されます