简体   繁体   中英

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?

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?

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM