我想部分专门化一个我无法更改的现有模板(std::tr1::hash
),以获取基类和所有派生类。原因是我使用奇怪的循环模板模式进行多态,而散列函数是在CRTP基类中实现的。如果我只想部分专门用于该CRTP基类,那么它很容易,我可以只写:如何部分专门化所有派生类型的类模板?
namespace std { namespace tr1 {
template <typename Derived>
struct hash<CRTPBase<Derived> >
{
size_t operator()(const CRTPBase<Derived> & base) const
{
return base.hash();
}
};
} }
但这种专业化不符合实际的派生类中,只有CRTPBase<Derived>
。我想要的是一种为Derived
编写部分专业化的方法,当且仅当它来自CRTPBase<Derived>
。我的伪代码
namespace std { namespace tr1 {
template <typename Derived>
struct hash<typename boost::enable_if<std::tr1::is_base_of<CRTPBase<Derived>, Derived>,
Derived>::type>
{
size_t operator()(const CRTPBase<Derived> & base) const
{
return base.hash();
}
};
} }
...但是,这并不工作,因为编译器不能告诉enable_if<condition, Derived>::type
是Derived
。如果我可以更改std::tr1::hash
,我只是添加另一个虚拟模板参数,使用boost::enable_if
,如enable_if
文档所建议的,但这显然不是一个很好的解决方案。有没有解决这个问题的方法?我是否必须为每个派生类创建unordered_set
或unordered_map
指定自定义哈希模板,或者完全专门针对每个派生类指定hash
?
看起来不错,谢谢。 – Doug 2009-06-24 10:49:37