Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Forward-declaring class from generic namespace (in std::hash

I'm struggling with a forward declaration. B references A, and A uses a std::vector of B. Both A and B are defined in the generic (no) namespace.

Forward declaring B in the header of A does the job for the members in A. Nevertheless, I defined the hash function for A in the same header file, and it causes trouble.

#include "B.h"
class B;
class A{
public:
   std::vector<B> bs; 
}

namespace std
{
template <>
struct hash<A>
{
    size_t operator()(const A& k) const
    {
        std::size_t seed = 0;
        boost::hash_combine(seed, k.foo);
        boost::hash_combine(seed, k.bar);
        for(B &b:k.bs){
            boost::hash_combine(seed, b.abc);
        }

        return seed;
    }
};
}

The function accesses the vector of B's and thus also requires the forward declaration. Nevertheless, it doesn't make use of the forward declaration in the parent header file. Unfortunately, I can't forward-declare it again within namespace std, because this will create ambiguity between the definitions. Any idea?

like image 536
Chris Avatar asked Aug 06 '26 01:08

Chris


1 Answers

You could move the definition of hash<A>::operator() into your source file. So:

// A.h
#include <vector>
#include <functional>

struct B;

struct A {
    std::vector<B> bs;
};

namespace std {
    template <>
    struct hash<A> {
        size_t operator()(const A& ) const;
    };
}
// A.cpp
#include "B.h"

// now, B is complete, so we can define operator()
size_t std::hash<A>::operator()(const A& k) const
{
    std::size_t seed = 0;
    boost::hash_combine(seed, k.foo);
    boost::hash_combine(seed, k.bar);
    for(const B& b : k.bs){
        boost::hash_combine(seed, b.abc);
    }

    return seed;
}
like image 162
Barry Avatar answered Aug 08 '26 16:08

Barry



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!