I am trying to write a hash function for my custom class, and make my code compatible with both gcc 11.1 and clang 12.0.0, but clang gives the warning/error:
<source>:30:25: warning: dependent nested name specifier 'std::hash<Base<U>>::' for friend class declaration is not supported; turning off access control for 'Base' [-Wunsupported-friend]
std::hash<Base<U>>::operator()(const Base<U>& b) const noexcept;
<source>:38:26: error: 'data_' is a private member of 'ns::Base<int>'
std::size_t seed = b.data_.size();
for the code below (also at https://godbolt.org/z/8Wsnqr5cb). How can I fix it to be compatible with both?
#include <set>
#include <utility>
#include <iostream>
// Forward declaration
namespace ns
{
template<typename T>
class Base;
}
/// Hash specialization declaration
template<typename T>
struct std::hash<ns::Base<T>>
{
std::size_t operator()(const ns::Base<T>& b) const noexcept;
};
namespace ns
{
template<typename T>
class Base {
std::set<T> data_;
public:
Base(const std::set<T>& data): data_{data} {}
template<typename U>
friend std::size_t
std::hash<Base<U>>::operator()(const Base<U>& b) const noexcept;
};
}
// In implementation file:
template<typename T>
std::size_t std::hash<ns::Base<T>>::operator()(const ns::Base<T>& b) const noexcept
{
std::size_t seed = b.data_.size();
for(const auto & x : b.data_)
seed ^= x;
return seed;
}
using namespace ns;
int main()
{
std::set<int> data({1,2,3,4,5});
Base<int> a(data);
std::cout << std::hash<Base<int>>{}(a) << std::endl;
}