Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
557 views
in Technique[技术] by (71.8m points)

c++ - std::hash template partial specialization

I wrote some class with template:

 template <class T, class Allocator = ::std::allocator<T> >
 class my_list;

I should write ::std::hash specializtion for this class. How can I do that? Simple partial specialization:

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 ...;
      }
  };
}

But I can't write simple partial specialization, because it forbidden by 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.

What can I do?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The paragraph you're quoting does not apply. You're partialy specialising a class template (std::hash), not a member class template of a standard library class or class template. std::hash is not a member of any class or class template.

For your case, paragraph 1 of the same section applies, and that allows specialisation when at least one user-defined type is involved (emphasis mine):

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...