How can I avoid having a hash function impl in my header if I want to use a tr1 unordered map for a custom type?

StackOverflow https://stackoverflow.com/questions/13094377

  •  14-07-2021
  •  | 
  •  

Question

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?

Was it helpful?

Solution

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 */ }

OTHER TIPS

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top