【发布时间】:2011-10-01 17:39:05
【问题描述】:
我想定义一个适用于给定基类的所有子类的 C++ 模板特化。这可能吗?
特别是,我想为 STL 的哈希 这样做。 hash 被定义为一个空的参数化模板,以及一系列针对特定类型的特化:
template<class _Key>
struct hash { };
template<>
struct hash<char>
{
size_t
operator()(char __x) const
{ return __x; }
};
template<>
struct hash<int>
{
size_t
operator()(int __x) const
{ return __x; }
};
...
我想这样定义:
template<class Base>
struct hash {
size_t operator()(const Base& b) const {
return b.my_hash();
}
};
class Sub : public Base {
public:
size_t my_hash() const { ... }
};
并且能够像这样使用它:
hash_multiset<Sub> set_of_sub;
set_of_sub.insert(sub);
但是,我的哈希模板与 STL 中的通用哈希模板冲突。有没有办法(可能使用特征)来定义适用于给定基类的所有子类的模板特化(无需修改 STL 定义)?
请注意,我知道只要需要这种哈希专业化,我就可以使用一些额外的模板参数来做到这一点,但如果可能的话,我想避免这种情况:
template<>
struct hash<Base> {
size_t operator()(const Base& b) const {
return b.my_hash();
}
};
....
// similar specialization of equal_to is needed here... I'm glossing over that...
hash_multiset<Sub, hash<Base>, equal_to<Base> > set_of_sub;
set_of_sub.insert(sub);
【问题讨论】:
-
如果冲突为什么不使用命名空间?
-
...这里的解决方案是把所有的派生类都以类似的方式命名,不太理想。
标签: c++ templates subclass template-specialization