我用模板写了一些类:
template <class T, class Allocator = ::std::allocator<T> >
class my_list;
我应该为这个类编写::std::hash 特化。我怎样才能做到这一点? 简单的偏特化:
namespace std {
template <class T, class Allocator>
class hash<my_list<T, Allocator> >{
public :
size_t operator()(const my_list<T, Allocator> &x ) const{
return ...;
}
};
}
但是我不能写简单的偏特化,因为它被 C++ ISO 禁止:
ISO/IEC 14882 Third edition 2011-09-01
17.6.4.2.1 Namespace std [namespace.std]
2 The behavior of a C++ program is undefined if it declares ... an explicit or partial specialization of any member class template of a standard library class or class template.
我能做什么?
最佳答案
您引用的段落不适用。您部分特化了类模板 (std::hash
),而不是标准库类的成员类模板,或者类模板。 std::hash
不是任何类或类模板的成员。
对于您的情况,同一部分的第 1 段适用,并且在涉及至少一种用户定义类型(强调我的)时允许专门化:
The behavior of a C++ program is undefined if it adds declarations or definitions to namespace
std
or to a namespace within namespace std unless otherwise specified. A program may add a template specialization for any standard library template to namespacestd
only if the declaration depends on a user-defined type and the specialization meets the standard library requirements for the original template and is not explicitly prohibited.
关于c++ - std::hash 模板偏特化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23339298/