0

I'm having some trouble defining hash and equality functions for objects. I'm using the objects as keys for std::unordered_map's. I have two keys aKey and unaccessibleKey. I can add an equailty operator overload to aKey, but I can't to unaccessibleKey because it's "unaccessible". I have tried doing the following, but I'm not sure if I'm using the right syntax for everything, and I don't know how to define an equality function for unaccessibleKey. Here's what I've tried:

struct aKeyHash
{
   std::size_t operator()(const aKey& k) const
   {
      return k.getnonconstmem()->nonconstfunc();
   };
}

struct unaccessibleKeyHash
{
   std::size_t operator()(const unaccessibleKey& k) const
   {
      return k.noncostmem;
   };
}

bool UnaccessibleEqualityFunction(const unaccessibleKey& p1, const unaccessibleKey& p2)
{???} //i dont know how to define this

std::unordered_map<aKey, std::unordered_map<unaccessibleKey, aValue, unaccessibleKeyHash, unaccessibleEqualityFunctions>, aKeyHash>

Am I doing this right (aside from the function that I don't know how to define)? As a side note, when I tried calling k.getnonconstmem()->nonconstfunction() I get an error.

It would be possible to use unaccessibleKey::nonconstmem as the key itself because it's actually a hashed int, but that may lead to complications later down the line that I don't want to deal with.

So my questions the are: 1. do I have the right syntax for the hashes, 2. how do I define the equality function, 3. why would I get the error with the const/nonconst mixing?

user3210986
  • 211
  • 2
  • 9
  • What is "unaccessible" key? Is it a private field? If so, you may find [this](http://stackoverflow.com/questions/13890747/hash-function-for-user-defined-class-how-to-make-friends) question useful. – yeputons Feb 03 '17 at 10:22
  • Your pseudo code leaves out too many important details. Please make a [mcve]. – nwp Feb 03 '17 at 10:24

1 Answers1

0
  1. do I have the right syntax for the hashes

The hash structures themselves have correct syntax. Whether the definitions of the hash functions are correct, depends on the definition of the target types. In particular, if getnonconstmem() is a non-const function, then calling it on a const reference is ill-formed. You may only call const functions on const objects.

  1. how do I define the equality function

Return true when the objects have equal logical state, and false otherwise. An example, which assumes that the state consists of a single member:

return p1.member == p2.member;
  1. why would I get the error with the const/nonconst mixing?

The shown code is not sufficient to explain why there would be errors. You will get errors if you try to modify, or call non-const functions on const objects, or any object through pointer or reference to const.

eerorika
  • 232,697
  • 12
  • 197
  • 326