简体   繁体   English

来自通用命名空间的前向声明类(在std :: hash中

[英]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. B引用A,A使用B的std :: vector.A 和B都在通用(无)命名空间中定义。

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. 在A的标题中正向声明B为A中的成员执行作业。尽管如此,我在同一个头文件中为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;
    }
};
}

The function accesses the vector of B's and thus also requires the forward declaration. 该函数访问B的向量,因此也需要前向声明。 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. 不幸的是,我无法在命名空间std中再次向前声明它,因为这会在定义之间产生歧义。 Any idea? 任何想法?

You could move the definition of hash<A>::operator() into your source file. 您可以将hash<A>::operator()的定义移动到源文件中。 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;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM