1

I need to hash a combination of four different things, comprising 20 bytes, as such I defined this:

struct holder
{
  char a;
  uint16_t b;
  uint64_t c;
  char d[9];
} __attribute((__packed__));

and then I can load one of the above and pass it to a hash function. So then I want my class Foo to have a std::tr1::unordered_map<holder, int> map. but in order to declare that in the header file for Foo, I need to include the definition of holder, the template specialization inside std::tr1 for hash for my type, and as a result the full hash function. Is there a way to not have all this code up in the header but still give my class this hashmap?

Kerrek SB
  • 464,522
  • 92
  • 875
  • 1,084
Palace Chan
  • 8,845
  • 11
  • 41
  • 93

2 Answers2

4

Simply declare the function in a header file, and define it at a cpp file.

This would look like:

// Header
namespace std { namespace tr1

// Define specialization
template<>
struct hash<holder>: unary_function<holder, size_t> {
    // Declare member
    size_t operator()(holder const&) const;
};

} }

// Source

// Define member
std::size_t std::tr1::hash<holder>::operator()(holder const&) const
{ /* implementation */ }
Luc Danton
  • 34,649
  • 6
  • 70
  • 114
K-ballo
  • 80,396
  • 20
  • 159
  • 169
  • It's also possible to specialize `std::tr1::hash::operator()` directly without specializing `std::tr1::hash` itself, but that function takes `holder` and thus must be declared as `template<> size_t hash::operator()(holder) const;`. – Luc Danton Oct 26 '12 at 21:55
0

The specialization of hash for holder can be in your header, but the implementation doesn't have to be. For an easy to understand way to do this, it (the specialization) can simply call a bog standard function on holder which you define in a cpp file.

Yakk - Adam Nevraumont
  • 262,606
  • 27
  • 330
  • 524