为嵌套类型定义哈希模板
Define Hash Template for Nested Types
我需要为一个类型定义一个散列函数,它依赖于一个类型,它又依赖于一个类型。我是这样累的:
我想,我需要在散列函数中为 G 提供一个模板参数,否则无法正确推导出 G,因为它本身需要一个模板参数,但我收到了警告。
template <typename P>
class G;
template <typename G>
class R;
template <typename P> std::size_t hash_code(const typename R<G<P>>::rs&);
namespace std
{
template <typename P>
struct hash<typename R<G<P>>::rs>
{
size_t operator()(const typename R<G<P>>::rs& rs) const
{
return hash_code(rs);
}
};
}
// definitions
template <typename P>
class G
{
public:
typedef P p;
typedef G<p> THIS;
typedef R<THIS> r;
std::unordered_set<r> Rset;
};
template <typename G>
class R
{
public:
typedef G g;
typedef typename G::p rs;
};
template<typename P>
size_t hash_code(const typename R<G<P>>::rs& rs)
{
size_t hash = 0x9e3779b9;
// hashing
return hash;
}
警告是:
hashtest.cpp:20:12: warning: class template partial specialization contains a template
parameter that cannot be deduced; this partial specialization will never be used
struct hash<typename R<G<P>>::rs>
^~~~~~~~~~~~~~~~~~~~~~~~~~
hashtest.cpp:19:24: note: non-deducible template parameter 'P'
template <typename P>
这正是我想通过在散列模板中进行模板化 G
来避免的问题。
如果这是您的实际代码而不是手动复制粘贴:
struct hash<typename R<G<P>::rs>
您在 P 后缺少右括号。
R<G<P>>::rs
是不可扣除的上下文(由于 ::
)。
无论如何它都会导致 P
这不是专业化。:
template <typename P> struct hash<P>
我需要为一个类型定义一个散列函数,它依赖于一个类型,它又依赖于一个类型。我是这样累的:
我想,我需要在散列函数中为 G 提供一个模板参数,否则无法正确推导出 G,因为它本身需要一个模板参数,但我收到了警告。
template <typename P>
class G;
template <typename G>
class R;
template <typename P> std::size_t hash_code(const typename R<G<P>>::rs&);
namespace std
{
template <typename P>
struct hash<typename R<G<P>>::rs>
{
size_t operator()(const typename R<G<P>>::rs& rs) const
{
return hash_code(rs);
}
};
}
// definitions
template <typename P>
class G
{
public:
typedef P p;
typedef G<p> THIS;
typedef R<THIS> r;
std::unordered_set<r> Rset;
};
template <typename G>
class R
{
public:
typedef G g;
typedef typename G::p rs;
};
template<typename P>
size_t hash_code(const typename R<G<P>>::rs& rs)
{
size_t hash = 0x9e3779b9;
// hashing
return hash;
}
警告是:
hashtest.cpp:20:12: warning: class template partial specialization contains a template
parameter that cannot be deduced; this partial specialization will never be used
struct hash<typename R<G<P>>::rs>
^~~~~~~~~~~~~~~~~~~~~~~~~~
hashtest.cpp:19:24: note: non-deducible template parameter 'P'
template <typename P>
这正是我想通过在散列模板中进行模板化 G
来避免的问题。
如果这是您的实际代码而不是手动复制粘贴:
struct hash<typename R<G<P>::rs>
您在 P 后缺少右括号。
R<G<P>>::rs
是不可扣除的上下文(由于 ::
)。
无论如何它都会导致 P
这不是专业化。:
template <typename P> struct hash<P>