c++ - std::hash 模板偏特化

标签 c++ templates c++11 std language-lawyer

我用模板写了一些类:

 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 namespace std 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/

相关文章:

c++ - 开启g++优化导致segmentation fault

c++ - std::unique_lock::try_lock_until() 是否忙等待?

c++ - std::set.insert 不会与自定义类一起编译

c++ - 为什么常量有类型修饰符?

c++ - 模板继承类派生基赋值

eclipse - 如何将参数传递到 eclipse-plugin 中的代码模板

c++ - 沿光栅化圆弧遍历像素

c++ - 可以阻止 cin 等待输入吗?

C++ 模板函数。错误 C2440 : 'return' : cannot convert from '_FwdIt1' to '_FwdIt1'

multithreading - Windows 和 Solaris 10 上的 std::async 性能