Clang error: Dependent nested name specifier for friend class declaration not supported

Viewed 117

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;
}
1 Answers

You can change the friend declaration only valid for the Base of current template parameter T, i.e. current instantiation.

template<typename T>
class Base {
    std::set<int> data_;

    public:
    Base(const std::set<int>& data): data_{data} {}

    friend std::size_t 
    std::hash<Base<T>>::operator()(const Base<T>& b) const noexcept;

    //or just
    //friend std::size_t 
    //std::hash<Base>::operator()(const Base& b) const noexcept;
};

Note that the effect is different with yours. With the above friend declaration, for example, given Base<int>, only std::hash<Base<int>>::operator() is the friend. With template friend declaration in your code, given Base<int>, all the possible instantiations like std::hash<Base<int>>::operator(), std::hash<Base<char>>::operator(), ... are friends.

Related