我想部分专用化一个我无法更改的现有模板(
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派生的
. 我的伪代码是
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
是
衍生的
. 如果我能改变的话
STD::Tr1::哈希
,我只需添加另一个要使用的虚拟模板参数。
boost::enable_if
,按照
enable_if
文档,但这显然不是一个很好的解决方案。有办法解决这个问题吗?是否必须在每个
unordered_set
或
unordered_map
我创建或完全专业化
hash
对于每个派生类?