Dou*_*oug 9 c++ partial-specialization derived-class crtp
我想部分专门化一个现有的模板,我无法改变(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();
}
};
} }
Run Code Online (Sandbox Code Playgroud)
但是这种专门化只与实际的派生类不匹配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();
}
};
} }
Run Code Online (Sandbox Code Playgroud)
......但是,这并不工作,因为编译器不能告诉大家,enable_if<condition, Derived>::type是Derived.如果我可以更改std::tr1::hash,我只需添加另一个虚拟模板参数boost::enable_if,如enable_if文档所建议的那样,但这显然不是一个很好的解决方案.有没有解决这个问题的方法?我是否必须在每个unordered_set或unordered_map我创建时指定自定义哈希模板,或者hash为每个派生类完全专门化?
以下代码中有两种变体.你可以选择更适合你.
template <typename Derived>
struct CRTPBase
{
size_t hash() const {return 0; }
};
// First case
//
// Help classes
struct DummyF1 {};
struct DummyF2 {};
struct DummyF3 {};
template<typename T> struct X;
// Main classes
template<> struct X<DummyF1> : CRTPBase< X<DummyF1> > {
int a1;
};
template<> struct X<DummyF2> : CRTPBase< X<DummyF2> > {
int b1;
};
// typedefs
typedef X<DummyF1> F1;
typedef X<DummyF2> F2;
typedef DummyF3 F3; // Does not work
namespace std { namespace tr1 {
template<class T>
struct hash< X<T> > {
size_t operator()(const CRTPBase< X<T> > & base) const
{
return base.hash();
}
};
}} // namespace tr1 // namespace std
//
// Second case
struct DummyS1 : CRTPBase <DummyS1> {
int m1;
};
//
template<typename T>
struct Y : T {};
//
typedef Y<DummyS1> S1;
namespace std { namespace tr1 {
template<class T>
struct hash< Y<T> > {
size_t operator()(const CRTPBase<T> & base) const
{
return base.hash();
}
};
}} // namespace tr1 // namespace std
void main1()
{
using std::tr1::hash;
F1 f1;
F2 f2;
F3 f3;
hash<F1> hf1; size_t v1 = hf1(f1); // custom hash functor
hash<F2> hf2; size_t v2 = hf2(f2); // custom hash functor
hash<F3> hf3; size_t v3 = hf3(f3); // error: standard hash functor
S1 s1;
hash<S1> hs1; size_t w1 = hs1(s1); // custom hash functor
}
Run Code Online (Sandbox Code Playgroud)