2

I am working with a Hashtable in C++. The hash function:

// Default hash function class
template <typename K>
struct KeyHash {
    unsigned long operator()(const K& key) const {
        return reinterpret_cast<unsigned long>(key) % TABLE_SIZE;
    }
};

Then when I declared hashtable as:

HashTable<int, std::string> hmap;

Its showing:

Invalid cast from 'int' type to 'unsigned_long_int'

Whats the problem with reinterpret_cast<unsigned long> here?

Kaidul
  • 15,409
  • 15
  • 81
  • 150

2 Answers2

9

You can't reinterpret_cast between two integer types, period. That's not what reinterpret_cast is for. If you want to cast between two integer types, use static_cast.

If your goal is to really "reinterpret the bit pattern" then you'll have to cast to reference. That is, reinterpret_cast<unsigned long&>(x) is valid if x is an lvalue of type int. But now you are getting into dangerous territory, as this is in general undefined behaviour, and will probably work on a 32-bit x86 platform but will do something bad on a 64-bit x86 platform where unsigned long is longer than int.

Brian Bi
  • 111,498
  • 10
  • 176
  • 312
  • +1 and AC for a good answer and not for down-voting me (people do without reason) :) – Kaidul Aug 30 '14 at 19:39
  • Accessing the value of `reinterpret_cast(x)` is _always_ UB; the cast is only syntactically valid. – ildjarn Aug 30 '14 at 19:58
  • It's always UB, but it's still possible that it behaves predictably on some implementations, just as with all UB. – Brian Bi Aug 30 '14 at 20:09
2

According to the C++ Standard (5.2.10 Reinterpret cast)

2 The reinterpret_cast operator shall not cast away constness (5.2.11). An expression of integral, enumeration, pointer, or pointer-to-member type can be explicitly converted to its own type; such a cast yields the value of its operand.

Use static_cast instead.

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335