I am trying to write a hash function for an internal class, which is a protected member of a larger class. In addition, the hash function should use protected members of the internal class (in this case, a string). So this is what it looks like without the hash function:
class MasterClass
{
public:
// Blah blah blah
protected:
class InternalClass
{
public:
// Blah blah blah 2
protected:
string m_Value;
};
unordered_map<InternalClass, uint> m_Example_Map;
};
Since I'm using InternalClass as a key in an unordered_map within MasterClass, I need to define the hash function.
I'm using the following references:
- C++ unordered_map using a custom class type as the key
- How to hash std::string?
- Hash function for user defined class. How to make friends? :)
But I'm in over my head. My best guess is something like this:
class MasterClass::InternalClass;
namespace std
{
template<> struct hash<MasterClass::InternalClass>
{
public:
size_t operator()(const MasterClass::InternalClass& i_Internal) const;
};
}
class MasterClass
{
public:
// Blah blah blah
protected:
class InternalClass
{
public:
// Blah blah blah 2
protected:
string m_Value;
};
unordered_map<InternalClass, uint> m_Example_Map;
friend struct std::hash<MasterClass::InternalClass>::operator()(const MasterClass::InternalClass& i_Name) const;
};
namespace std
{
template<> size_t hash<MasterClass::InternalClass>::operator()(const MasterClass::InternalClass& i_Internal) const
{
return(std::hash<std::string>{}(*i_Internal.m_Value);
}
}
However, this is riddled with compiler errors, including "Invalid friend declaration" and "explicit specialization of class "std::hash" must precede its first use (at line 719 of "C:\Program Files (x86)\Microsoft Visual Studio\2017\Enterprise\VC\Tools\MSVC\14.16.27023\include\type_traits")"
How can I define my hash function for the protected, internal class (using protected members of the internal class)?