我在努力争取向前宣言。 B引用A,并且A使用B的std::vector。 A和B都在通用(否) namespace 中定义。

在A的 header 中向前声明B可以对A中的成员进行处理。尽管如此,我在同一 header 文件中为A定义了哈希函数,这会造成麻烦。

#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;
    }
};
}

该函数访问B的 vector ,因此也需要前向声明。但是,它没有使用父头文件中的forward声明。不幸的是,我无法在命名空间std中再次对其进行前向声明,因为这将在定义之间造成歧义。任何的想法?

最佳答案

您可以将hash<A>::operator()的定义移至源文件中。所以:

// 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;
}

09-30 13:51
查看更多