reinterpret_cast 的一个实际用途是在哈希函数中,即,通过让两个不同的值几乎不以相同的索引结尾的方式将值映射到索引。

#include <iostream>
using namespace std;

// Returns a hash code based on an address
unsigned short Hash( void *p ) {
   unsigned int val = reinterpret_cast<unsigned int>( p );
   return ( unsigned short )( val ^ (val >> 16));
}

using namespace std;
int main() {
   int a[20];
   for ( int i = 0; i < 20; i++ )
      cout << Hash( a + i ) << endl;
}

Output: 
64641
64645
64889
64893
64881
64885
64873
64877
64865
64869
64857
64861
64849
64853
64841
64845
64833
64837
64825
64829

该索引随后被标准 C 样式强制转换截断为函数的返回类型。

相关文章:

  • 2022-03-01
  • 2022-01-13
  • 2021-07-30
  • 2021-12-05
  • 2021-08-19
  • 2021-12-10
  • 2022-03-09
猜你喜欢
  • 2022-12-23
  • 2022-02-26
  • 2021-07-11
  • 2022-01-18
  • 2022-12-23
  • 2022-12-23
相关资源
相似解决方案