Take the 2-minute tour ×

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?

share|improve this question

2 Answers 2

up vote 3 down vote accepted

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
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 */ }
share|improve this answer
It's also possible to specialize std::tr1::hash<holder>::operator() directly without specializing std::tr1::hash<holder> itself, but that function takes holder and thus must be declared as template<> size_t hash<holder>::operator()(holder) const;. –  Luc Danton Oct 26 '12 at 21:55

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.

share|improve this answer

Your Answer


